# Multi-stage build for tenant-registry.
# Produces two binaries:
#   /tenant-registry  — long-running API server
#   /migrate          — one-shot schema migrator (Orca init container in prod)
#   /erpmock          — ERPNext stand-in for staging (decision 18; cmd/erpmock)

FROM golang:1.26-alpine AS build
# eMudhra (Mozilla bug 2083449, Oct 2026): current ca-certificates, and fail
# the build if the bundle still holds "emSign ECC Root CA - G3" (the grep
# pattern is a line of that certificate).
RUN apk upgrade --no-cache ca-certificates-bundle ca-certificates \
    && ! grep -qF bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g /etc/ssl/certs/ca-certificates.crt
# Go >= 1.26.10 distrusts the eMudhra intermediates itself (CVE-2026-111943).
RUN case "$(go env GOVERSION)" in go1.26.[0-9]|go1.2[0-5].*) echo "$(go env GOVERSION) lacks the eMudhra distrust, need >= 1.26.10" >&2; exit 1;; esac
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
# Build version and commit for GET /version (CI passes both; portal#64).
ARG VERSION=dev
ARG COMMIT=
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w -X git.breakpilot.com/platform/tenant-registry/internal/buildinfo.Version=${VERSION} -X git.breakpilot.com/platform/tenant-registry/internal/buildinfo.Commit=${COMMIT}" -o /out/tenant-registry ./cmd/server && \
    CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/migrate         ./cmd/migrate && \
    CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/erpmock         ./cmd/erpmock && \
    CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/erpsetup        ./cmd/erpsetup && \
    CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/invoiceintake   ./cmd/invoiceintake

FROM gcr.io/distroless/static-debian12:nonroot
# The build stage's updated bundle: distroless ships one that still trusts emSign ECC Root CA - G3.
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
WORKDIR /
COPY --from=build /out/tenant-registry /tenant-registry
COPY --from=build /out/migrate         /migrate
COPY --from=build /out/erpmock         /erpmock
COPY --from=build /out/erpsetup        /erpsetup
COPY --from=build /out/invoiceintake   /invoiceintake
USER nonroot:nonroot
EXPOSE 8090
# CMD (not ENTRYPOINT) so orca's `cmd` can select /erpmock, /migrate or /invoiceintake in the
# same image. The server applies migrations itself with MIGRATE_ON_START=true.
CMD ["/tenant-registry"]
