ARG TARGETOS=linux
ARG TARGETARCH=amd64

FROM golang:1.27.1-bookworm@sha256:69a7b9788769bec032d238959b61854e9ae87f57be9029ec04e9885fabf99195 AS build

ARG TARGETOS
ARG TARGETARCH
ARG VERSION=dev
ARG REVISION=unknown
ARG BUILD_TIME=unknown

WORKDIR /src
ENV GO111MODULE=on \
    CGO_ENABLED=0 \
    GOPROXY=https://goproxy.cn,direct \
    GOWORK=off

COPY go.mod go.sum ./
RUN go mod download
COPY . .

RUN BUILD_FLAGS="-s -w -X git.yuntuo.hk/k2safe/orbit/internal/buildinfo.Version=${VERSION} -X git.yuntuo.hk/k2safe/orbit/internal/buildinfo.Revision=${REVISION} -X git.yuntuo.hk/k2safe/orbit/internal/buildinfo.BuiltAt=${BUILD_TIME}" \
    && CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="${BUILD_FLAGS}" -o /out/orbit ./cmd/orbit \
    && CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="${BUILD_FLAGS}" -o /out/orbit-migrate ./cmd/orbit-migrate \
    && CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="${BUILD_FLAGS}" -o /out/orbit-admin ./cmd/orbit-admin

FROM scratch

ARG VERSION=dev
ARG REVISION=unknown
ARG BUILD_TIME=unknown
LABEL org.opencontainers.image.title="Orbit" \
      org.opencontainers.image.version="${VERSION}" \
      org.opencontainers.image.revision="${REVISION}" \
      org.opencontainers.image.created="${BUILD_TIME}"

COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY --from=build /out/orbit /usr/local/bin/orbit
COPY --from=build /out/orbit-migrate /usr/local/bin/orbit-migrate
COPY --from=build /out/orbit-admin /usr/local/bin/orbit-admin

USER 65532:65532
ENTRYPOINT ["/usr/local/bin/orbit"]
