# syntax=docker/dockerfile:1

# ---- build ----
# Pinned by digest (S3): a moving tag is a supply-chain door — the image that
# built yesterday's binary must be provably the image that builds today's.
FROM swift:6.1-noble@sha256:98ee3a8469ce2a9c2f543ef2577939ab44e2dfc9b5ed710732a59e5dd64f9c4a AS build
WORKDIR /src

# Resolve dependencies first so source edits don't invalidate the dep layer.
COPY Package.swift Package.resolved ./
RUN swift package resolve

# Tests/ is copied because Package.swift declares a test target; without it
# SwiftPM can't locate that target's sources and fails the whole package.
COPY Sources ./Sources
COPY Tests ./Tests
RUN --mount=type=cache,target=/src/.build,sharing=locked \
    swift build -c release --product flamenet-relay \
    && install -m 0755 \
       "$(swift build -c release --product flamenet-relay --show-bin-path)/flamenet-relay" \
       /usr/local/bin/flamenet-relay

# ---- runtime ----
FROM swift:6.1-noble-slim@sha256:007349ced8e0a8a9abd4e9bc246c8dae4e52cc608aec8d19765c5d94c64cd84f AS runtime
RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates curl libsqlite3-0 \
    && rm -rf /var/lib/apt/lists/* \
    && useradd --create-home --shell /usr/sbin/nologin relay

COPY --from=build /usr/local/bin/flamenet-relay /usr/local/bin/flamenet-relay

# Vapor resolves Resources/Views (Leaf) and Public/ relative to the working
# directory, so the runtime image needs both and needs to start in /app.
WORKDIR /app
COPY Resources ./Resources
COPY Public ./Public

# SQLite DB + attachments live here; mount a volume to persist across runs.
RUN mkdir -p /data/attachments && chown -R relay:relay /data
ENV FN_DB=/data/relay.sqlite \
    FN_ATTACHMENTS_DIR=/data/attachments
VOLUME ["/data"]

# The commit this image was built from, for error reports
# (`--build-arg FN_RELEASE=<sha>`). Last, so a new sha does not invalidate
# the layers above. Unset leaves it empty and reports carry no release.
ARG FN_RELEASE=
ENV FN_RELEASE=${FN_RELEASE}

USER relay
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=5 \
    CMD curl -fsS http://127.0.0.1:8080/health || exit 1

ENTRYPOINT ["flamenet-relay"]
CMD ["serve", "--hostname", "0.0.0.0", "--port", "8080"]
