# syntax=docker/dockerfile:1
FROM golang:1.24 AS builder

WORKDIR /build

RUN apt-get update && apt-get install -y --no-install-recommends git bc && rm -rf /var/lib/apt/lists/*

COPY go.work go.work.sum* ./
COPY shared/go/ja4common/ ./shared/go/ja4common/
COPY services/sentinel/go.mod services/sentinel/go.sum* ./services/sentinel/
COPY services/correlator/go.mod services/correlator/go.sum* ./services/correlator/

WORKDIR /build/services/correlator
RUN --mount=type=cache,target=/go/pkg/mod go mod download

COPY services/correlator/ /build/services/correlator/

ARG SKIP_TESTS=false
RUN --mount=type=cache,target=/go/pkg/mod \
    if [ "$SKIP_TESTS" = "false" ]; then \
        go test -race -coverprofile=coverage.txt -covermode=atomic ./... && \
        echo "=== Coverage Report ===" && \
        go tool cover -func=coverage.txt | grep total && \
        TOTAL=$(go tool cover -func=coverage.txt | grep total | awk '{gsub(/%/, "", $3); print $3}') && \
        echo "Total coverage: ${TOTAL}%" && \
        if (( $(echo "$TOTAL < 60" | bc -l) )); then \
            echo "ERROR: Coverage ${TOTAL}% is below 60% threshold"; \
            exit 1; \
        fi && \
        echo "Coverage check passed!"; \
    else \
        echo "Skipping tests (SKIP_TESTS=true)"; \
    fi

RUN --mount=type=cache,target=/go/pkg/mod \
    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
    -ldflags="-w -s" -o /usr/bin/correlator ./cmd/logcorrelator

FROM scratch AS runtime
COPY --from=builder /usr/bin/correlator /usr/bin/correlator
COPY --from=builder /build/services/correlator/config.example.yml /etc/correlator/correlator.yml
ENTRYPOINT ["/usr/bin/correlator"]
CMD ["-config", "/etc/correlator/correlator.yml"]
