# Precompile key slow-to-build dependencies
FROM --platform=$BUILDPLATFORM golang:1.24-alpine AS go-deps
WORKDIR /linkerd-build
COPY go.mod go.sum ./
COPY bin/install-deps bin/
RUN go mod download
ARG TARGETARCH
RUN ./bin/install-deps $TARGETARCH

## compile controller service
FROM go-deps AS golang
WORKDIR /linkerd-build
COPY controller/gen controller/gen
COPY pkg pkg
COPY charts charts
COPY controller controller
COPY charts/patch charts/patch
COPY charts/partials charts/partials
COPY multicluster multicluster

ARG TARGETARCH
RUN CGO_ENABLED=0 GOOS=linux GOARCH=$TARGETARCH go build -o /out/controller -tags prod -mod=readonly -ldflags "-s -w" ./controller/cmd

FROM --platform=$BUILDPLATFORM ghcr.io/linkerd/dev:v47-rust-musl AS policy
ARG BUILD_TYPE="release"
WORKDIR /build
RUN mkdir -p target/bin
COPY Cargo.toml Cargo.lock .
COPY policy-controller policy-controller
RUN cargo new policy-test --lib
ENV CARGO="cargo auditable"
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    just-cargo fetch
ARG TARGETARCH
# Install cross compiler toolchains
RUN case "$TARGETARCH" in \
        amd64) true ;; \
        arm64) apt-get -y update && apt-get install --no-install-recommends -y binutils-aarch64-linux-gnu ;; \
    esac && rm -rf /var/lib/apt/lists/*
# Enable tokio runtime metrics
ENV RUSTFLAGS="--cfg tokio_unstable"
RUN --mount=type=cache,target=target \
    --mount=type=cache,target=/usr/local/cargo/registry \
    target=$(case "$TARGETARCH" in \
        amd64) echo x86_64-unknown-linux-musl ;; \
        arm64) echo aarch64-unknown-linux-musl ;; \
        *) echo "unsupported architecture: $TARGETARCH" >&2; exit 1 ;; \
    esac) && \
    just-cargo CFLAGS_aarch64_unknown_linux_musl="" profile=$BUILD_TYPE target=$target build --package=linkerd-policy-controller && \
    mkdir /out && mv "target/$target/$BUILD_TYPE/linkerd-policy-controller" /out/

## package runtime
FROM scratch
LABEL org.opencontainers.image.source=https://github.com/linkerd/linkerd2
COPY LICENSE /linkerd/LICENSE
COPY --from=golang /out/controller /controller
COPY --from=policy /out/linkerd-policy-controller /
# for heartbeat (https://versioncheck.linkerd.io/version.json)
COPY --from=golang /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

ARG LINKERD_VERSION
ENV LINKERD_CONTAINER_VERSION_OVERRIDE=${LINKERD_VERSION}
ENTRYPOINT ["/controller"]
