# syntax=docker/dockerfile:1

# ---- Build stage ----
FROM golang:1.26-alpine AS builder

ENV CGO_ENABLED=0 GOOS=linux

ARG VERSION=docker
ARG COMMIT=docker
ARG BUILD_TIME=unknown
ARG PROJECT=git.loyso.art/frx/kurious

WORKDIR /src

# Cache module downloads.
COPY go.mod go.sum ./
RUN go mod download

# Copy the rest of the source.
# Generated files (templ *_templ.go, mockery mocks) are committed, so no
# generation step is required here.
COPY . .

# Build the web server and the healthcheck probe.
RUN go build -trimpath \
        -ldflags "-X ${PROJECT}.version=${VERSION} -X ${PROJECT}.commit=${COMMIT} -X ${PROJECT}.buildTime=${BUILD_TIME}" \
        -o /out/kuriweb ./cmd/kuriweb \
    && go build -trimpath -o /out/healthcheck ./cmd/healthcheck

# Bake a default config into the image (config files are gitignored locally,
# so the image must be self-contained).
RUN echo '{"log":{"level":"info","format":"json"},"http":{"listen_addr":":8080","mount_live":false},"sqlite":{"dsn":"/tmp/kurious.sqlite","shutdown_timeout":"10s"},"db_engine":"sqlite","tracing":{"type":"stdout","show_metrics":false}}' > /out/config.json

# ---- Final stage ----
FROM gcr.io/distroless/static-debian12

LABEL org.opencontainers.image.title="kuriousweb" \
      org.opencontainers.image.source="git.loyso.art/frx/kurious"

COPY --from=builder /out/kuriweb     /kuriweb
COPY --from=builder /out/healthcheck /healthcheck
COPY --from=builder /out/config.json /etc/kurious/config.json

# static-debian12 ships a "nonroot" user (uid 65532).
USER nonroot:nonroot

EXPOSE 8080

ENTRYPOINT ["/kuriweb"]
CMD ["/etc/kurious/config.json"]

# Distroless static has no shell/curl, so probing is done via the tiny
# healthcheck binary built above.
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD ["/healthcheck", "http://127.0.0.1:8080/healthz"]
