# sm64coopdx headless dedicated server
# Requires baserom.us.z64 (SM64 US ROM) in build context

# --- Build stage ---
FROM ubuntu:jammy AS build

RUN apt-get update && apt-get install -y \
    binutils-mips-linux-gnu \
    bsdmainutils \
    build-essential \
    libcapstone-dev \
    pkgconf \
    python3 \
    libz-dev \
    libcurl4-openssl-dev \
    git \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /sm64

RUN git clone --depth 1 https://github.com/coop-deluxe/sm64coopdx.git .

COPY baserom.us.z64 .

# Patch: add missing float.h include (GCC 11 strictness)
RUN sed -i '1i #include <float.h>' src/engine/math_util.c

# Patch: fix platform.c fallback — upstream renamed functions but forgot the #else branch
RUN sed -i 's/const char \*sys_exe_path(void) {/const char *sys_exe_path_dir(void) {\n    return ".";\n}\n\nconst char *sys_resource_path(void) {\n    return ".";\n}\n\nconst char *sys_exe_path(void) {/' src/pc/platform.c

RUN make HEADLESS=1 DISCORD_SDK=0 COOPNET=0 -j$(nproc)

# --- Runtime stage ---
FROM ubuntu:jammy

RUN apt-get update && apt-get install -y \
    libcurl4 \
    libz1 \
    && rm -rf /var/lib/apt/lists/*

RUN useradd -m -s /bin/bash sm64

WORKDIR /server

COPY --from=build /sm64/build/us_pc/ .
COPY --from=build /sm64/baserom.us.z64 .

RUN mkdir -p /server/mods /server/save && chown -R sm64:sm64 /server

USER sm64

EXPOSE 7777/udp

ENV SM64_PORT=7777
ENV SM64_PLAYERS=16

ENTRYPOINT ["sh", "-c", "./sm64coopdx --server ${SM64_PORT} --headless --playercount ${SM64_PLAYERS} --skip-intro"]
