# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 Bryan Joshua Pedini

ARG GO_BUILDER=golang
ARG GO_VERSION=1.27-alpine
FROM ${GO_BUILDER}:${GO_VERSION} AS build
ARG GO_OS=linux
ARG GO_ARCH=amd64
ARG APP_VERSION=latest
ARG COMMIT_ID=undefined
RUN apk add --no-cache ca-certificates
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=${GO_OS} GOARCH=${GO_ARCH} go build -trimpath \
    -ldflags="-w -s -X 'main.APP_VERSION=${APP_VERSION}' -X 'main.COMMIT_ID=${COMMIT_ID}'" -o /app .

FROM build AS testenv
ARG STATICCHECK_VERSION=v0.8.2
RUN apk add --no-cache gcc musl-dev && go install honnef.co/go/tools/cmd/staticcheck@${STATICCHECK_VERSION}
ENV CGO_ENABLED=1

FROM testenv AS test
RUN unformatted=$(gofmt -l .) && if [ -n "$unformatted" ]; then echo "gofmt: $unformatted" >&2; exit 1; fi
RUN go vet ./... && go vet -tags integration ./...
RUN staticcheck ./... && staticcheck -tags integration ./...
RUN go test -race -count=1 ./...

FROM testenv AS integration
CMD ["go", "test", "-tags", "integration", "-race", "-count=1", "-run", "TestIntegration", "-v", "./..."]

FROM scratch
ARG GIT_HOST=git.bjphoster.com
ARG REPO_ORG=source
ARG REPO_NAME=coredns-web-ui
ARG APP_VERSION=latest
ARG COMMIT_ID=undefined
LABEL org.opencontainers.image.source="https://${GIT_HOST}/${REPO_ORG}/${REPO_NAME}" \
      org.opencontainers.image.revision="${COMMIT_ID}" \
      org.opencontainers.image.version="${APP_VERSION}" \
      org.opencontainers.image.licenses="GPL-2.0-or-later"
COPY --from=build /app /app
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/cert.pem
USER 65532:65532
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 CMD ["/app", "healthcheck"]
ENTRYPOINT ["/app"]
