# syntax=docker/dockerfile:1.6
#
# Multi-stage, multi-arch build for nginx-logtail.
#
# A single `docker buildx build --platform linux/amd64,linux/arm64`
# produces a proper multi-arch manifest without a qemu-emulated builder:
# the builder runs on the host's $BUILDPLATFORM and Go cross-compiles
# to each requested $TARGETARCH via the Makefile's build-amd64 /
# build-arm64 targets. Both BUILDPLATFORM and TARGETARCH are populated
# automatically by buildx.
#
# One runtime image contains all four binaries; docker-compose.yml
# picks which one each service runs via `command:`.
#
# Driven from the Makefile:
#   make docker           # native arch, --load into local daemon
#   make docker-push      # multi-arch manifest, pushed to the registry

# =============================================================================
# Builder — compiles all four binaries on the host's native arch.
# =============================================================================
FROM --platform=$BUILDPLATFORM golang:1.24-alpine AS builder

# TARGETARCH (amd64, arm64, ...) is supplied by buildx; VERSION/COMMIT/DATE
# come in as --build-arg from `make docker` / `make docker-push`.
ARG TARGETARCH
ARG VERSION=dev
ARG COMMIT=unknown
ARG DATE=unknown

# make drives the build. git lets the Makefile stamp a commit hash via
# `git rev-parse` when --build-arg COMMIT isn't supplied; when it is,
# the command-line override below wins and git is only needed to avoid
# the fallback branch warning.
RUN apk add --no-cache make git

WORKDIR /src

# Cache Go modules so code-only rebuilds skip the download.
COPY go.mod go.sum ./
RUN go mod download

COPY . .

# Generated proto files are checked in, but `docker COPY` resets mtimes,
# which can make `make` think they are stale relative to the .proto
# source. Touch them so the regen rule is skipped.
RUN touch proto/logtailpb/logtail.pb.go proto/logtailpb/logtail_grpc.pb.go

# The Makefile's build-<arch> target sets GOOS=linux GOARCH=<arch>
# CGO_ENABLED=0 and emits build/<arch>/<binary> with the usual -ldflags
# version injection. Forwarding VERSION/COMMIT_HASH/DATE on the command
# line stamps the values supplied by --build-arg into the binaries.
RUN make VERSION=$VERSION COMMIT_HASH=$COMMIT DATE=$DATE build-$TARGETARCH

# =============================================================================
# Runtime — scratch, no OS, no shell. All four binaries.
# =============================================================================
FROM scratch
ARG TARGETARCH
COPY --from=builder /src/build/$TARGETARCH/collector  /usr/local/bin/collector
COPY --from=builder /src/build/$TARGETARCH/aggregator /usr/local/bin/aggregator
COPY --from=builder /src/build/$TARGETARCH/frontend   /usr/local/bin/frontend
COPY --from=builder /src/build/$TARGETARCH/cli        /usr/local/bin/cli
