# Kvitt server image (SPEC §10.3). Build context: server/. Built on the owner's M4 Mac, never on the Pi:
#   docker build --platform linux/arm64 -f server/Dockerfile -t kvitt-server:dev server/
# linux/amd64 builds the same way (--platform linux/amd64; emulated on the Mac, slow). The Rust version is the one
# pinned in rust-toolchain.toml; the two always change together.

# ---- stage 1: build --------------------------------------------------------------------------------------------
FROM docker.io/library/rust:1.99.1-bookworm AS build
ARG TARGETARCH
# Parallel rustc jobs. Unset (the default) means cargo's own default, one per core, as on the Mac. The Gitea runner
# on the Pi 3 (1 GB RAM) passes --build-arg CARGO_BUILD_JOBS=1. Passed as an explicit --jobs flag, only when set,
# so an empty value never reaches cargo.
ARG CARGO_BUILD_JOBS
# The full bookworm image carries gcc 12 and make, which aws-lc-sys (rustls via reqwest, jsonwebtoken) needs to
# compile its C code; no cmake binary is needed (checked 2026-10-18, docs/spikes/pi-image-arm64.md).
# Use the image's toolchain as is; rust-toolchain.toml names the same version but would also pull clippy/rustfmt.
ENV RUSTUP_TOOLCHAIN=1.99.1 \
    CARGO_TERM_COLOR=never
WORKDIR /src
COPY . .
# Native build for the target platform: aarch64-unknown-linux-gnu on arm64 (generic Armv8-A, no
# target-cpu=native: the Pi 3 is a Cortex-A53), x86_64-unknown-linux-gnu on amd64.
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/src/target,id=kvitt-target-${TARGETARCH} \
    case "${TARGETARCH:-arm64}" in \
      arm64) triple=aarch64-unknown-linux-gnu ;; \
      amd64) triple=x86_64-unknown-linux-gnu ;; \
      *) echo "unsupported TARGETARCH ${TARGETARCH}" >&2; exit 1 ;; \
    esac \
    && echo "cargo build jobs: ${CARGO_BUILD_JOBS:-default (one per core)}" \
    && cargo build --release --locked --target "$triple" ${CARGO_BUILD_JOBS:+--jobs $CARGO_BUILD_JOBS} \
         -p kvitt-server -p kvitt-import \
    && mkdir -p /out \
    && cp "target/$triple/release/kvitt-server" "target/$triple/release/kvitt-import" /out/

# ---- stage 2: runtime ------------------------------------------------------------------------------------------
# glibc + libgcc, no shell, no package manager. Pinned by digest (multi-arch index of :nonroot). It carries the
# Debian CA bundle at /etc/ssl/certs/ca-certificates.crt, which rustls-platform-verifier reads to reach Google.
FROM gcr.io/distroless/cc-debian12:nonroot@sha256:9dac0a79194e45a7da0158a9c6da57b217585af0786db3845d1f0ec1a0dd182f
COPY --from=build /out/kvitt-server /out/kvitt-import /usr/local/bin/
# Runs as uid/gid 10001 with a read-only root filesystem; /data is the only writable volume and /secrets is
# mounted read-only (SPEC §8.9). Listens on 8080 inside the compose network.
USER 10001:10001
ENV KVITT_DATA_DIR=/data
EXPOSE 8080
ENTRYPOINT ["kvitt-server"]
CMD ["serve"]
