# ---- build ------------------------------------------------------------------
# Swift 6.2, not 6.0: the dependency graph (swift-log, async-http-client,
# swift-nio) declares tools versions 6.1 and 6.2, and an older toolchain
# fails resolution outright rather than falling back.
FROM swift:6.2-noble AS build

WORKDIR /build

# Resolve dependencies first so edits to source do not invalidate the layer.
COPY Package.swift Package.resolved ./
RUN swift package resolve --skip-update

COPY Sources ./Sources
COPY Tests ./Tests
COPY scripts ./scripts

# Static stdlib keeps the runtime image free of a Swift installation.
RUN swift build -c release --product EnclaveAccounts --static-swift-stdlib

WORKDIR /staging
RUN BIN="$(swift build --package-path /build -c release --show-bin-path)" \
 && cp "$BIN/EnclaveAccounts" ./ \
 && find -L "$BIN" -regex '.*\.resources$' -exec cp -Ra {} ./ \;


# ---- runtime ----------------------------------------------------------------
FROM ubuntu:noble

RUN apt-get update \
 && apt-get install -y --no-install-recommends ca-certificates tzdata libcurl4 libxml2 curl \
 && rm -rf /var/lib/apt/lists/*

# Never run as root. The server needs no write access to its own image.
RUN useradd --user-group --create-home --system --skel /dev/null --home-dir /app enclave

WORKDIR /app
COPY --from=build --chown=enclave:enclave /staging /app
USER enclave:enclave

EXPOSE 8100
# No ENTRYPOINT: compose selects which binary this container runs.
CMD ["./EnclaveAccounts", "serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8100"]
