# Development bootstrap tag. Promotion requires an approved immutable digest.
ARG UBUNTU_IMAGE=ubuntu:24.04
FROM ${UBUNTU_IMAGE} AS toolchain
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates cmake ninja-build g++-14 \
    && rm -rf /var/lib/apt/lists/*
WORKDIR /source

FROM toolchain AS ci-toolchain
RUN apt-get update \
    && apt-get install -y --no-install-recommends clang-19 clang-format-19 \
       clang-tidy-19 libclang-rt-19-dev \
    && rm -rf /var/lib/apt/lists/*
RUN dpkg-query -W

# Keep expensive compiler/package layers independent from source changes.
FROM ci-toolchain AS ci-source
# Compile parallelism for the native CI stages; each clang analysis/ASan job can take
# 1-2 GiB, so raising it needs matching runner memory.
ARG CI_BUILD_JOBS=4
ENV CI_BUILD_JOBS=${CI_BUILD_JOBS}
COPY CMakeLists.txt CMakePresets.json .clang-format .clang-tidy ./
COPY cmake/ cmake/
COPY include/ include/
COPY src/ src/
COPY apps/ apps/
COPY tests/ tests/
COPY experiments/ experiments/
COPY tools/ tools/
COPY third_party/ third_party/

FROM ci-source AS ci-checks
RUN bash tools/ci/linux-check.sh checks

FROM ci-source AS ci-tsan
RUN cmake --preset tsan -DCMAKE_CXX_COMPILER=clang++-19 \
    && cmake --build --preset tsan --parallel "${CI_BUILD_JOBS}"
CMD ["ctest", "--preset", "tsan", "--no-tests=error", "--timeout", "120"]

FROM ci-source AS ci-client
# X11 window + software regression; native GPU probes remain separate platform evidence.
RUN apt-get update && apt-get install -y --no-install-recommends \
      libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxtst-dev xvfb xauth \
    && rm -rf /var/lib/apt/lists/*
# Lifecycle tests deliberately quit/reopen SDL: retain the virtual X server with
# -noreset through those cycles, matching a persistent desktop display server.
RUN cmake -P tools/prepare-sdl3.cmake \
    && cmake -P tools/prepare-imgui.cmake \
    && cmake --preset client-probe -DCMAKE_CXX_COMPILER=clang++-19 -DCMAKE_C_COMPILER=clang-19 \
       -DEVO_BUILD_CLIENT=ON -DEVO_BUILD_UI_PROBE=ON -DEVO_ENABLE_TIDY=ON -DSDL_X11=ON -DSDL_WAYLAND=OFF \
    && cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests evo-client-panel-tests evo-client-bindings-tests evo-client-auth-tests --parallel "${CI_BUILD_JOBS}" \
    && ctest --preset client-probe --no-tests=error \
    && xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-probe --renderer software \
    && for cycle in 1 2 3; do xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-ui-probe --renderer software --cycles 1; done \
    && xvfb-run -a -s "-screen 0 1280x1024x24 -noreset" env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-lifecycle-tests \
    && cmake --preset client-probe -DEVO_BUILD_CLIENT=ON -DEVO_SANITIZER=address -DEVO_ENABLE_TIDY=OFF \
    && cmake --build build/client-probe --target evo-client-state-tests evo-ui-probe evo-client evo-client-lifecycle-tests evo-client-environment-tests evo-client-organism-tests evo-client-ui-model-tests evo-client-panel-tests evo-client-bindings-tests evo-client-auth-tests --parallel "${CI_BUILD_JOBS}" \
    && ctest --preset client-probe --no-tests=error \
    && for cycle in 1 2 3; do xvfb-run -a env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-ui-probe --renderer software --cycles 1; done \
    && xvfb-run -a -s "-screen 0 1280x1024x24 -noreset" env SDL_VIDEO_DRIVER=x11 ./build/client-probe/evo-client-lifecycle-tests

FROM ci-source AS ci-network
# Explicit pinned Mbed TLS preparation (ADR-0082); codec, admission, dev grants and
# TLS 1.3 loopback with static analysis, then again under ASan/UBSan.
RUN cmake -P tools/prepare-mbedtls.cmake \
    && cmake --preset network -DCMAKE_CXX_COMPILER=clang++-19 -DCMAKE_C_COMPILER=clang-19 \
       -DEVO_ENABLE_TIDY=ON \
    && cmake --build --preset network --parallel "${CI_BUILD_JOBS}" \
    && ctest --preset network --no-tests=error \
    && cmake --preset network -DEVO_SANITIZER=address -DEVO_ENABLE_TIDY=OFF \
    && cmake --build --preset network --parallel "${CI_BUILD_JOBS}" \
    && ctest --preset network --no-tests=error

FROM ci-source AS ci-ecs
# Explicit experiment preparation; normal configure/runtime remains dependency-free.
RUN cmake -P tools/prepare-entt.cmake \
    && cmake --preset release -B build/ecs -DCMAKE_CXX_COMPILER=g++-14 -DEVO_BUILD_ECS_EXPERIMENT=ON \
    && cmake --build build/ecs --target evo-ecs-experiment --parallel "${CI_BUILD_JOBS}" \
    && ctest --test-dir build/ecs -R ecs-experiment --output-on-failure --no-tests=error \
    && ./build/ecs/evo-ecs-experiment --measure \
    && stat -c 'experiment_executable_bytes=%s' build/ecs/evo-ecs-experiment
RUN cmake --preset asan -B build/ecs-asan -DCMAKE_CXX_COMPILER=clang++-19 -DEVO_BUILD_ECS_EXPERIMENT=ON \
    && cmake --build build/ecs-asan --target evo-ecs-experiment --parallel "${CI_BUILD_JOBS}" \
    && ctest --test-dir build/ecs-asan -R ecs-experiment --output-on-failure --no-tests=error
RUN cmake --preset analysis -B build/ecs-analysis -DCMAKE_CXX_COMPILER=clang++-19 -DEVO_BUILD_ECS_EXPERIMENT=ON \
    && cmake --build build/ecs-analysis --target evo-ecs-experiment --parallel "${CI_BUILD_JOBS}" \
    && ctest --test-dir build/ecs-analysis -R ecs-experiment --output-on-failure --no-tests=error

# M8.2 offline deployment-policy check (ADR-0069): Ubuntu's python3-yaml only, no
# cluster access. Fails the build when an isolation or World0 invariant breaks.
FROM ${UBUNTU_IMAGE} AS ci-deploy
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
    && apt-get install -y --no-install-recommends python3 python3-yaml curl ca-certificates \
    && rm -rf /var/lib/apt/lists/*
WORKDIR /source
# Pinned, checksum-verified kustomize for the rendered-output checks (ADR-0088).
COPY tools/ci/prepare-kustomize.sh tools/ci/
RUN bash tools/ci/prepare-kustomize.sh /usr/local/bin
COPY deploy/ deploy/
COPY tools/ci/deploy-policy-check.py tools/ci/deploy-policy-selftest.py tools/ci/
COPY tools/ops/ tools/ops/
COPY tools/backup/ tools/backup/
COPY tools/ci/ops-lib-check.sh tools/ci/
RUN python3 tools/ci/deploy-policy-check.py && python3 tools/ci/deploy-policy-selftest.py \
    && bash tools/ci/ops-lib-check.sh
# M8.5: monitoring configuration and alert tests with the pinned images' own tools.
COPY --from=quay.io/prometheus/prometheus@sha256:6976aa8a60fec930796ce5772b8d12da7a318a5daa8d40d69c5c7819a05eeed7 /bin/promtool /usr/local/bin/promtool
COPY --from=quay.io/prometheus/alertmanager@sha256:e9733bafb1bdef9b00e25a21f8f99dc26a22224bf16641ad754d1649f4c3357a /bin/amtool /usr/local/bin/amtool
COPY tools/ci/monitoring-check.sh tools/ci/
RUN bash tools/ci/monitoring-check.sh

FROM ci-toolchain AS postgres-toolchain
RUN apt-get update && apt-get install -y --no-install-recommends \
      curl bzip2 make flex bison perl libssl-dev zlib1g-dev pkg-config \
    && rm -rf /var/lib/apt/lists/*
# The toolchain installs versioned compilers only; there is no bare cc/gcc.
COPY tools/prepare-postgres.sh tools/prepare-postgres.sh
# Compile parallelism for the PostgreSQL stages. Each clang ASan/analysis job can take
# 1-2 GiB, so raising this needs matching runner memory (see .gitea/workflows/build.yaml).
ARG PG_BUILD_JOBS=6
RUN CC=gcc-14 PG_BUILD_JOBS=${PG_BUILD_JOBS} bash tools/prepare-postgres.sh

# PostgreSQL itself is prepared once. Source/test changes invalidate only the
# layers below, while postgres-tools can reuse this image without compiling the
# full C++ test matrix.
FROM postgres-toolchain AS postgres-build
ARG PG_BUILD_JOBS=6
COPY CMakeLists.txt CMakePresets.json .clang-format .clang-tidy ./
COPY cmake/ cmake/
COPY include/ include/
COPY src/ src/
COPY apps/ apps/
COPY tests/ tests/
COPY experiments/ experiments/
COPY tools/ tools/
COPY third_party/ third_party/
COPY migrations/ migrations/
# M10.4c (ADR-0092): evo-server includes the opt-in QUIC session listener; the pinned
# Mbed TLS and msquic sources are prepared explicitly and verified against their hashes.
RUN cmake -P tools/prepare-mbedtls.cmake
RUN cmake -P tools/prepare-msquic.cmake
RUN cmake --preset release -B build/postgres -DCMAKE_CXX_COMPILER=g++-14 \
      -DCMAKE_C_COMPILER=gcc-14 -DEVO_BUILD_NETWORK=ON \
      -DEVO_BUILD_QUIC=ON -DEVO_BUILD_POSTGRES=ON \
      -DPostgreSQL_ROOT=/source/.cache/postgres/install \
    && cmake --build build/postgres --target evo-server evo-session-probe evo-world-clone evo-grant-broker \
      evo-admin-api --parallel "${PG_BUILD_JOBS}"

FROM postgres-build AS postgres-test-build
ARG PG_BUILD_JOBS=6
# PostgreSQL-only test changes skip the native checks job (tools/ci/ci-paths.sh), so the
# repository format check also runs here.
RUN cmake -DFORMATTER=/usr/bin/clang-format-19 -DSOURCE_ROOT=/source -P tools/check-format.cmake
RUN cmake --build build/postgres --target evo-postgres-tests --parallel "${PG_BUILD_JOBS}"
RUN cmake --preset analysis -B build/postgres-analysis -DCMAKE_CXX_COMPILER=clang++-19 \
      -DCMAKE_C_COMPILER=clang-19 -DEVO_BUILD_NETWORK=ON \
      -DEVO_BUILD_POSTGRES=ON -DPostgreSQL_ROOT=/source/.cache/postgres/install \
    && cmake --build build/postgres-analysis --target evo-postgres-tests --parallel "${PG_BUILD_JOBS}"
RUN cmake --preset asan -B build/postgres-asan -DCMAKE_CXX_COMPILER=clang++-19 \
      -DCMAKE_C_COMPILER=clang-19 -DEVO_BUILD_NETWORK=ON \
      -DEVO_BUILD_POSTGRES=ON -DPostgreSQL_ROOT=/source/.cache/postgres/install \
    && cmake --build build/postgres-asan --target evo-postgres-tests --parallel "${PG_BUILD_JOBS}"

FROM postgres-test-build AS ci-postgres
# Test-only ephemeral TLS credentials and a standard-library loopback port picker.
RUN apt-get update && apt-get install -y --no-install-recommends openssl python3 \
    && rm -rf /var/lib/apt/lists/* \
    && openssl version && python3 --version \
    && useradd --uid 10001 --no-create-home evo
USER 10001:10001
# Full qualification once on the release build. ASan/UBSan reruns everything that
# executes its instrumented binaries; the uninstrumented clang-tidy build reruns only
# the C++ suite. SQL-only checks do not change with compiler flags.
RUN bash tools/ci/postgres-check.sh --full /source/build/postgres/evo-postgres-tests \
    && bash tools/ci/postgres-check.sh --suite-only /source/build/postgres-analysis/evo-postgres-tests \
    && bash tools/ci/postgres-check.sh --sanitizer /source/build/postgres-asan/evo-postgres-tests

FROM postgres-toolchain AS postgres-tools
RUN apt-get update && apt-get install -y --no-install-recommends libssl3t64 zlib1g ca-certificates \
    && rm -rf /var/lib/apt/lists/* \
    && groupadd --gid 10001 evo && useradd --uid 10001 --gid 10001 --no-create-home evo
COPY --from=postgres-toolchain /source/.cache/postgres/install/bin/psql /opt/postgres/bin/psql
# M8.7 backups (ADR-0074): the same pinned PostgreSQL build's dump tools.
COPY --from=postgres-toolchain /source/.cache/postgres/install/bin/pg_dump /opt/postgres/bin/pg_dump
COPY --from=postgres-toolchain /source/.cache/postgres/install/bin/pg_restore /opt/postgres/bin/pg_restore
COPY --from=postgres-toolchain /source/.cache/postgres/install/lib/libpq.so* /opt/postgres/lib/
COPY --from=postgres-toolchain /source/.cache/postgres/postgresql-18.6/COPYRIGHT /usr/share/doc/evo-postgres/COPYRIGHT
COPY tools/migrate-postgres.sh /opt/evo/tools/migrate-postgres.sh
COPY tools/backup/backup-world.sh /opt/evo/tools/backup-world.sh
COPY migrations/ /opt/evo/migrations/
ENV PATH="/opt/postgres/bin:${PATH}" LD_LIBRARY_PATH=/opt/postgres/lib
USER 10001:10001
ENTRYPOINT ["bash", "/opt/evo/tools/migrate-postgres.sh"]

# M7.8 development region server image (ADR-0066): evo-server with the pinned
# libpq, non-root, no credentials. Connection secrets are mounted at runtime only.
FROM ${UBUNTU_IMAGE} AS server-runtime
RUN apt-get update && apt-get install -y --no-install-recommends       libstdc++6 libgcc-s1 libssl3t64 zlib1g ca-certificates     && rm -rf /var/lib/apt/lists/*     && groupadd --gid 10001 evo     && useradd --uid 10001 --gid 10001 --no-create-home        --home-dir /nonexistent --shell /usr/sbin/nologin evo
COPY --from=postgres-build /source/build/postgres/evo-server /usr/local/bin/evo-server
# M8.3 operations tool: check-store qualification, clone and history audit.
COPY --from=postgres-build /source/build/postgres/evo-world-clone /usr/local/bin/evo-world-clone
# ADR-0131 grant broker (Keycloak tokens to session grants); its own Deployment.
COPY --from=postgres-build /source/build/postgres/evo-grant-broker /usr/local/bin/evo-grant-broker
# ADR-0182 read-only admin API and the portal's static files; its own Deployment.
COPY --from=postgres-build /source/build/postgres/evo-admin-api /usr/local/bin/evo-admin-api
COPY apps/evo-admin-api/portal/ /usr/local/share/evo-admin-portal/
COPY --from=postgres-build /source/.cache/postgres/install/lib/libpq.so* /opt/postgres/lib/
COPY --from=postgres-build /source/build/postgres/msquic/bin/Release/libmsquic.so* /opt/msquic/lib/
COPY --from=postgres-build /source/.cache/postgres/postgresql-18.6/COPYRIGHT /usr/share/doc/evo-postgres/COPYRIGHT
RUN chmod 1777 /tmp
ENV LD_LIBRARY_PATH=/opt/postgres/lib:/opt/msquic/lib
USER 10001:10001
WORKDIR /tmp
EXPOSE 9100
ENTRYPOINT ["/usr/local/bin/evo-server"]

FROM ci-source AS build
RUN cmake --preset release -B build/container \
      -DCMAKE_CXX_COMPILER=g++-14 -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=/opt/evo/bin \
    && cmake --build build/container --parallel "${CI_BUILD_JOBS}" \
    && ctest --test-dir build/container --output-on-failure --no-tests=error --timeout 120
RUN dpkg-query -W > /opt/evo/build-packages.txt

FROM ${UBUNTU_IMAGE} AS runtime
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
    && apt-get install -y --no-install-recommends libstdc++6 libgcc-s1 \
    && rm -rf /var/lib/apt/lists/* \
    && groupadd --gid 10001 evo \
    && useradd --uid 10001 --gid 10001 --no-create-home \
       --home-dir /nonexistent --shell /usr/sbin/nologin evo
COPY --from=build /opt/evo/bin/evo-sim /usr/local/bin/evo-sim
COPY --from=build /opt/evo/build-packages.txt /usr/share/evo/build-packages.txt
USER 10001:10001
WORKDIR /tmp
ENTRYPOINT ["/usr/local/bin/evo-sim"]
CMD ["--seed", "123456", "--ticks", "1000"]
