# Lint stage
# golangci/golangci-lint:v2.12.2-alpine
FROM golangci/golangci-lint:v2.12.2-alpine@sha256:91b27804074a0bacea298707f016911e60cf0cdbc6c7bf5ccacb5f0606d18d60 AS lint

RUN apk add --no-cache make build-base

WORKDIR /src

# Copy go mod files first for better layer caching
COPY go.mod go.sum ./
RUN go mod download

# Copy source code
COPY . .

# Run formatting check and linter
RUN make fmt-check
RUN make lint

# Build stage
# golang:1.26.4-alpine
FROM golang:1.26.4-alpine@sha256:3ad57304ad93bbec8548a0437ad9e06a455660655d9af011d58b993f6f615648 AS builder

# Depend on lint stage passing
COPY --from=lint /src/go.sum /dev/null

# Install build deps plus the sqlite3 and zstd CLIs the tests/tool shell out
# to, and git, which the build step below derives the version with
RUN apk add --no-cache make build-base sqlite zstd git

WORKDIR /src

# Copy go mod files first for better layer caching
COPY go.mod go.sum ./
RUN go mod download

# Copy source code
COPY . .

# Run tests
RUN make test

# Build (pure Go, no CGO required since we use modernc.org/sqlite).
# The version stamped into the binary: the VERSION build argument when one is
# given, otherwise `git describe --tags --always` of the .git the build context
# carries: the tag on a tagged commit, tag-N-gHASH on a commit after one, the
# short commit when no tag is reachable. A context that carries .git and still
# yields no version fails the build. With neither, as from a source tarball,
# the binary reports dev.
ARG VERSION
RUN version="${VERSION:-$(git describe --tags --always)}"; \
    if [ -e .git ] && { [ -z "$version" ] || [ "$version" = dev ] || \
        [ "$version" = unknown ]; }; then \
        echo "no version could be derived although the build context carries .git" >&2; \
        exit 1; \
    fi; \
    CGO_ENABLED=0 go build -ldflags="-X main.Version=${version:-dev}" \
        -o /bsdaily ./cmd/bsdaily

# Runtime stage
# alpine:3.21
FROM alpine:3.21@sha256:48b0309ca019d89d40f670aa1bc06e426dc0931948452e8491e3d65087abc07d

# bsdaily shells out to sqlite3, zstdmt, zstdcat at runtime
RUN apk add --no-cache ca-certificates sqlite zstd

# Copy binary from builder
COPY --from=builder /bsdaily /usr/local/bin/bsdaily

ENTRYPOINT ["/usr/local/bin/bsdaily"]
