#
# syntax=docker/dockerfile:1.7

# Build stage
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build

ARG SOURCE_REPO=https://git.wylab.me/wylab/wylab-station-14.git
ARG SOURCE_REF=master
ARG TARGETPLATFORM
ARG TARGET_PLATFORM=auto

# Install dependencies needed to build and package the server
RUN --mount=type=cache,target=/var/cache/apt \
    --mount=type=cache,target=/var/lib/apt/lists \
    apt-get update && \
    apt-get install -y --no-install-recommends git python3 unzip

WORKDIR /src

# Clone the wylab-station-14 source
RUN git clone "${SOURCE_REPO}" content
WORKDIR /src/content
RUN git checkout "${SOURCE_REF}"

# Initialize submodules / engine checkout
RUN python3 RUN_THIS.py --quiet

# Build and package the server for the requested platform
RUN --mount=type=cache,target=/root/.nuget/packages \
    if [ "${TARGET_PLATFORM}" = "auto" ]; then \
        case "${TARGETPLATFORM:-linux/amd64}" in \
            "linux/amd64") SERVER_RID="linux-x64" ;; \
            "linux/arm64") SERVER_RID="linux-arm64" ;; \
            "linux/arm/v7"|"linux/arm/v6") SERVER_RID="linux-arm" ;; \
            *) echo "Unsupported TARGETPLATFORM '${TARGETPLATFORM}'. Set TARGET_PLATFORM explicitly."; exit 1 ;; \
        esac; \
    else \
        SERVER_RID="${TARGET_PLATFORM}"; \
    fi && \
    echo "Building server runtime for ${SERVER_RID} (docker TARGETPLATFORM=${TARGETPLATFORM:-unknown})" && \
    dotnet run --project Content.Packaging/Content.Packaging.csproj server \
        --platform "${SERVER_RID}" \
        --configuration Release

# Extract packaged build into the filesystem layout the runtime stage expects
RUN mkdir -p /ss14-default && \
    unzip "release/SS14.Server_${TARGET_PLATFORM}.zip" -d /ss14-default/

# Server stage
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS server

RUN apt-get update && \
    apt-get install -y --no-install-recommends ca-certificates python3 && \
    rm -rf /var/lib/apt/lists/*

# Copy from the build stage
COPY --from=build /ss14-default /ss14-default
COPY update_build_metadata.py /update_build_metadata.py

# Expose necessary ports
EXPOSE 1212/tcp
EXPOSE 1212/udp
EXPOSE 8080/tcp

# Set volume
VOLUME [ "/ss14" ]

# Add configurations (files go to root, not publish/)
ADD appsettings.yml /ss14-default/appsettings.yml
ADD server_config.toml /ss14-default/server_config.toml

COPY start.sh /start.sh
RUN python3 /update_build_metadata.py /ss14-default/server_config.toml || true && \
    chmod +x /start.sh

# Set the entry point for the container
ENTRYPOINT ["/start.sh"]
