# Lint phase. The linter is invoked directly rather than through `make
# lint` or `script/lint`, which are themselves a docker build and would
# recurse into a daemon that does not exist in a build step.
#
# golangci/golangci-lint v2.12.2 (built with go1.26.2), 2026-05-06
FROM golangci/golangci-lint@sha256:5cceeef04e53efe1470638d4b4b4f5ceefd574955ab3941b2d9a68a8c9ad5240 AS lint

WORKDIR /src

COPY go.mod go.sum ./
RUN go mod download

COPY . .

RUN golangci-lint run --config .golangci.yml ./...

# Test phase, same shape and for the same reason. The go directive in
# go.mod is a minimum, so this Go may be newer than the linter's. The
# Debian image rather than the Alpine one, because the race detector
# needs the C compiler it carries.
#
# golang 1.27.1-trixie, 2026-09-19
FROM golang@sha256:3b77fc618ec235a1ab412de7737f120dd507c57e8d87de4cbb7994fb94275ed5 AS test

WORKDIR /src

COPY go.mod go.sum ./
RUN go mod download

COPY . .

RUN go test -count=1 -timeout 90s -race -cover ./... || \
    { echo "--- Rerunning with -v for details ---"; \
      go test -count=1 -timeout 90s -race -v ./...; exit 1; }

# Build stage, and the last one: a plain `docker build .` names no
# target and so builds this one. Nothing is wanted from the two phases
# above; the copies are what make BuildKit build them first, so this
# image cannot be produced unless lint and test passed. The image an
# app's Dockerfile builds FROM comes with milestone 2
# (https://git.eeqj.de/sneak/smallwebwaf/issues/12); until then this
# stage builds the binary and can run it.
#
# golang 1.27.1-trixie, 2026-09-19
FROM golang@sha256:3b77fc618ec235a1ab412de7737f120dd507c57e8d87de4cbb7994fb94275ed5

COPY --from=lint /src/go.sum /dev/null
COPY --from=test /src/go.sum /dev/null

WORKDIR /src

COPY go.mod go.sum ./
RUN go mod download

COPY . .

# The version is computed on the host and passed in, because
# .dockerignore excludes .git.
ARG VERSION=dev
RUN CGO_ENABLED=0 go build -trimpath \
    -ldflags="-s -w -X main.Version=${VERSION}" \
    -o /usr/local/bin/smallwebwaf ./cmd/smallwebwaf

EXPOSE 8080
ENTRYPOINT ["/usr/local/bin/smallwebwaf"]
