# Use SQL Server 2022 Express for smaller footprint
FROM mcr.microsoft.com/mssql/server:2022-latest

# Set required environment variables
ENV ACCEPT_EULA=Y \
    MSSQL_PID=Express \
    SA_PASSWORD=YourStrong@Passw0rd \
    DROP_DATABASE=false \
    PATH="/opt/mssql-tools/bin:${PATH}"

# Install sqlcmd utility
USER root
RUN apt-get update && \
    apt-get install -y wget software-properties-common gnupg2 && \
    wget -qO- https://packages.microsoft.com/keys/microsoft.asc | apt-key add - && \
    add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/20.04/mssql-server-2022.list)" && \
    apt-get update && \
    ACCEPT_EULA=Y apt-get install -y mssql-tools unixodbc-dev && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# Create app directory and schemas subdirectory in one layer
WORKDIR /usr/src/app
RUN mkdir -p schemas

# Copy all SQL files in a single layer to reduce image size
COPY ./sql-server/schemas/*.sql ./schemas/
COPY ./sql-server/init.sql ./
COPY ./sql-server/setup.sh ./

# Fix line endings and make setup script executable
RUN sed -i 's/\r$//' setup.sh && \
    chmod +x setup.sh

# Switch back to mssql user
USER mssql

# Start SQL Server with our setup script
CMD /bin/bash ./setup.sh