# Build the toolchain stage on its own and pass it back in to skip the apt step:
#   docker build -f modules/server/Dockerfile --target toolchain -t tw_toolchain .
#   docker build -f modules/server/Dockerfile --build-arg TOOLCHAIN_IMAGE=tw_toolchain .
ARG TOOLCHAIN_IMAGE=toolchain

# ── toolchain stage ──────────────────────────────────────────────────────────
FROM ubuntu:24.04 AS toolchain

ENV DEBIAN_FRONTEND=noninteractive

RUN apt-get update && apt-get install -y --no-install-recommends \
    clang \
    libstdc++-14-dev \
    cmake \
    ninja-build \
    mold \
    git \
    ca-certificates \
    pkg-config \
    glslang-tools \
    libvulkan-dev \
    libsdl2-dev \
    libprotobuf-dev protobuf-compiler \
    libpq-dev \
    libpqxx-dev \
    && rm -rf /var/lib/apt/lists/*

ENV CC=clang
ENV CXX=clang++

# ── build stage ──────────────────────────────────────────────────────────────
FROM ${TOOLCHAIN_IMAGE} AS builder

WORKDIR /src
COPY . .

# glm, entt, Jolt, spdlog, expected, Catch2 and tracy are cloned at configure time
RUN cmake -B /build -G Ninja -DCMAKE_BUILD_TYPE=Release \
    && cmake --build /build --target tw_server

# Stage the shared libraries the binary was linked against; the runtime image has
# no package manager. glibc and its loader stay behind, they come with that image.
RUN mkdir -p /rootfs/usr/lib/x86_64-linux-gnu \
    && ldd /build/modules/server/tw_server \
        | awk '/=> \//{ print $3 }' \
        | grep -vE '/(libc|libm|libdl|libpthread|librt|libresolv|libanl)\.so' \
        | xargs -I{} cp -L {} /rootfs/usr/lib/x86_64-linux-gnu/

# ── runtime stage ─────────────────────────────────────────────────────────────
FROM gcr.io/distroless/cc-debian13:nonroot

COPY --from=builder /rootfs/ /
COPY --from=builder /build/modules/server/tw_server /usr/local/bin/tw_server

# player connections, zone-server peering
EXPOSE 8101/udp 8102/udp

ENTRYPOINT ["/usr/local/bin/tw_server"]
