# syntax=docker/dockerfile:1.7
#
# SS14 Watchdog Docker Image (based on LiamAEdwards/SS14-Docker-Linux-Server)
# Downloads game server from CDN and builds SS14.Watchdog
#

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

ARG TARGETPLATFORM

# Update and install necessary tools
RUN apt-get -y update && \
    apt-get -y install curl unzip wget git jq

# Determine platform RID based on Docker TARGETPLATFORM
RUN if [ "${TARGETPLATFORM:-linux/amd64}" = "linux/arm64" ]; then \
        echo "linux-arm64" > /tmp/platform_rid; \
    else \
        echo "linux-x64" > /tmp/platform_rid; \
    fi && \
    echo "Building for platform: $(cat /tmp/platform_rid)"

# Download and extract SS14 server from WYLAB CDN
RUN PLATFORM_RID=$(cat /tmp/platform_rid) && \
    SERVER_URL=$(curl -sL https://cdn.wylab.me/fork/wylab/manifest | \
    jq -r ".builds | to_entries | sort_by(.value.time) | last | .value.server.\"${PLATFORM_RID}\".url") && \
    echo "Downloading server from: $SERVER_URL" && \
    wget -O SS14.Server.zip "$SERVER_URL" && \
    unzip SS14.Server.zip -d /ss14-default/

# Download and build Watchdog
RUN PLATFORM_RID=$(cat /tmp/platform_rid) && \
    wget https://github.com/space-wizards/SS14.Watchdog/archive/refs/heads/master.zip -O Watchdog.zip && \
    unzip Watchdog.zip -d Watchdog && \
    cd Watchdog/SS14.Watchdog-master && \
    dotnet publish SS14.Watchdog -c Release -r "${PLATFORM_RID}" --no-self-contained -o /ss14-default/publish

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

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

# Install necessary tools
RUN apt-get -y update && apt-get -y install unzip && \
    rm -rf /var/lib/apt/lists/*

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

# Set volume
VOLUME [ "/ss14" ]

# Add configurations
COPY appsettings.yml /ss14-default/publish/appsettings.yml
COPY server_config.toml /ss14-default/publish/server_config.toml

COPY start.sh /start.sh
RUN chmod +x /start.sh

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