# syntax=docker/dockerfile:1

# dev target: full toolchain + debug tools for development and debugging.
# Base image and compiler are the latest stable (ubuntu:26.04 ships gcc/g++ 16).
FROM ubuntu:26.04 AS dev

ENV DEBIAN_FRONTEND=noninteractive

# Optional apt mirror override, e.g. --build-arg APT_MIRROR=http://mirrors.tuna.tsinghua.edu.cn/ubuntu
ARG APT_MIRROR=""
RUN if [ -n "$APT_MIRROR" ]; then \
        sed -i -e "s|http://archive.ubuntu.com/ubuntu|${APT_MIRROR}|g" \
               -e "s|http://security.ubuntu.com/ubuntu|${APT_MIRROR}|g" \
               -e "s|http://ports.ubuntu.com/ubuntu-ports|${APT_MIRROR}|g" \
               /etc/apt/sources.list /etc/apt/sources.list.d/*.sources 2>/dev/null || true; \
    fi

RUN --mount=type=cache,target=/var/lib/apt,sharing=locked \
    --mount=type=cache,target=/var/cache/apt,sharing=locked \
    for attempt in 1 2 3 4 5; do \
        apt-get -o Acquire::Retries=5 update && break; \
        echo "apt-get update failed (attempt $attempt), retrying"; \
        sleep 5; \
    done \
    && apt-get -o Acquire::Retries=5 install -y --no-install-recommends \
        build-essential \
        ca-certificates \
        cmake \
        g++-16 \
        gdb \
        git \
        libsdl3-dev \
        ninja-build \
        pkg-config \
    && rm -rf /var/lib/apt/lists/*

# Pin the toolchain to GCC 16 (the distro default is still GCC 15).
ENV CC=gcc-16
ENV CXX=g++-16
RUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-16 100 \
    && update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-16 100 \
    && update-alternatives --install /usr/bin/c++ c++ /usr/bin/g++-16 100

WORKDIR /work
COPY . .

# C++26 modules need CMake >= 3.28, the Ninja generator and a module-aware gcc.
RUN cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
    && cmake --build build -j \
    && ctest --test-dir build --output-on-failure

# deploy target: runtime dependencies + final binary, minimal and fast.
FROM ubuntu:26.04 AS deploy

ENV DEBIAN_FRONTEND=noninteractive

RUN apt-get -o Acquire::Retries=5 update \
    && apt-get -o Acquire::Retries=5 install -y --no-install-recommends \
        libsdl3-0 \
        libstdc++6 \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=dev /work/build/bin/openra3 /app/openra3

ENTRYPOINT ["/app/openra3"]
