# syntax=docker/dockerfile:1

# ── base stage: git, which both the build and the runtime stage need ─────────
# The build stage fetches the private dredd-core with git; at RUNTIME GitPython wraps the system git
# binary (the facade). Installing it once, ahead of any COPY, keeps this layer cached when
# requirements change (e.g. a dredd-core repin) instead of re-running apt in the runtime stage.
FROM python:3.12-slim AS base

RUN apt-get update \
 && apt-get install -y --no-install-recommends git \
 && rm -rf /var/lib/apt/lists/*

# ── build stage: resolve dependencies, including the private one ─────────────
# `dredd-core` is a private repository on the Haski Gitea pinned by tag in requirements.txt, so installing it
# needs `git` (from the base stage) and a credential the runtime image should never have.
#
# The credential arrives as a BuildKit SECRET, not a build argument. A build arg is baked into the
# image history — `docker history` prints it — so a pushed image would publish the token to anyone
# who can pull it. A secret mount exists only for the duration of the one RUN that uses it.
# `GIT_CONFIG_*` scopes the rewrite to that same process, so nothing is written to a gitconfig
# that could survive into a layer either.
#
# Build with:  DREDD_CORE_TOKEN=... docker compose build     (compose passes it as the secret)
# (The same build as Sygna's, which its CI runs end to end.)
FROM base AS build

WORKDIR /build
COPY requirements.txt .
# `required=true` only fails when the secret is ABSENT — compose passes an unset DREDD_CORE_TOKEN as
# an EMPTY secret, which would otherwise surface much later as a confusing git auth error. Hence the
# `test -s`. `tr -d` drops a stray CR/LF from a pasted token (git would echo a key containing one).
RUN --mount=type=secret,id=dredd_core_token,required=true \
    test -s /run/secrets/dredd_core_token \
      || { echo "build secret dredd_core_token is empty - export DREDD_CORE_TOKEN" >&2; exit 1; }; \
    GIT_CONFIG_COUNT=1 \
    GIT_CONFIG_KEY_0="url.http://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@77.216.148.202:3000/.insteadOf" \
    GIT_CONFIG_VALUE_0="http://77.216.148.202:3000/" \
    pip install --no-cache-dir --prefix=/install -r requirements.txt

# ── vendor stage: the console's third-party browser code, pinned and verified ─
# ReaderJS (git, by full commit SHA), tesseract.js + its WASM core + language models and PDF.js (npm
# tarballs, by their integrity hashes). Served by this backend from static/, so no CDN code ever runs
# in Galena's origin (Atrium#68, R2). A mismatch fails the build. No credential needed: all public.
FROM base AS vendor
COPY scripts/fetch_vendor.py /tmp/fetch_vendor.py
RUN python /tmp/fetch_vendor.py /vendor

# ── runtime stage: no credential, no compiler ────────────────────────────────
FROM base

COPY --from=build /install /usr/local

WORKDIR /app
COPY . .

# The static console, which this backend serves itself (app/main.py mounts it at "/"; no proxy
# sits in front of it). It lives in the repo's frontend/, outside this build context, so it
# arrives as a NAMED build context: compose passes `additional_contexts: { frontend: ./frontend }`,
# and a bare build from backend/ needs `docker build --build-context frontend=../frontend .`.
# /frontend is exactly where main.py's default (two levels above app/main.py) looks.
COPY --from=frontend . /frontend
COPY --from=vendor /vendor /frontend/static

RUN useradd -m app && mkdir -p /data && chown -R app /data /app
ENV DATA_DIR=/data
USER app
# A default identity + main as the default branch keep GitPython operations clean.
RUN git config --global user.email "galena@localhost" \
    && git config --global user.name "Galena" \
    && git config --global init.defaultBranch main \
    && git config --global --add safe.directory '*'

EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=5s --retries=10 \
  CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/api/v1/health').status==200 else 1)"
# Which proxy may set X-Forwarded-For / -Proto. On the platform that is Atrium's front door, pinned
# to its network in Atrium's compose.yaml; standalone nothing sits in front, so the default trusts
# loopback only (an empty value means the same - `:-` treats empty as unset). Never `*` on a
# published port: the audit log's client IPs and the cookie's Secure flag (the request scheme) would
# then be the client's to choose.
ENV FORWARDED_ALLOW_IPS=
# The path prefix the front door strips before it reaches us - ROOT_PATH=/galena when Galena runs as
# a module of the platform (Atrium forwards /galena/* without it), empty (the default here) when it
# is served at the root. uvicorn PREPENDS it to the incoming path: set one half without the other
# and you get either a doubled prefix (404 everywhere) or server-generated URLs that escape the
# prefix. app/config.py reads the same variable, so FastAPI's root_path agrees.
ENV ROOT_PATH=
# `sh -c` so the variables expand at start-up; `exec` so uvicorn gets SIGTERM directly.
# --no-server-header: nothing stands in front of uvicorn, so it must not announce `Server: uvicorn` itself.
CMD ["sh", "-c", "exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --root-path \"$ROOT_PATH\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-127.0.0.1}\" --no-server-header"]
