# Source: https://raw.githubusercontent.com/kubernetes/autoscaler/refs/heads/master/cluster-autoscaler/Dockerfile.amd64
ARG builder_image=docker.io/library/golang:1.27@sha256:3680233e3204827fbdc66088528ae6d4b3d034f51d03a99d454f6de034888244
ARG BASEIMAGE=gcr.io/distroless/static:nonroot-${TARGETARCH}

FROM --platform=$BUILDPLATFORM ${builder_image} AS builder
ARG GOPROXY

ARG TARGETOS
ARG TARGETARCH
ENV GOOS=$TARGETOS
ENV GOARCH=$TARGETARCH

RUN git clone https://github.com/kubernetes/autoscaler /src/autoscaler \
 && cd /src/autoscaler/cluster-autoscaler \
 && git checkout cluster-autoscaler-1.32.0

WORKDIR /src/autoscaler/cluster-autoscaler
COPY fix-downscale.diff /fix-downscale.diff
RUN git apply /fix-downscale.diff

# go build never compiles a _test.go, so nothing else runs the tests of the
# packages the patch touches. Each package is tested from its own directory,
# below the clone root because the patch names paths from there: that finds
# the module it belongs to, and an empty list runs nothing.
# The list is read into a variable first: a for loop drops the exit status
# of a command substitution, so a patch git cannot read would leave the list
# empty and the step green.
# The stage sets GOOS and GOARCH to the target for the whole stage, so the
# tests drop them: a test binary built for another architecture cannot run
# on the build host without emulation.
RUN cd /src/autoscaler && files=$(git apply --numstat /fix-downscale.diff) || exit 1; \
    for dir in $(printf '%s\n' "$files" | cut -f3 | grep '\.go$' | xargs -r -n1 dirname | sort -u); do \
      (cd "$dir" && env -u GOOS -u GOARCH go test .) || exit 1; \
    done

RUN make build

FROM $BASEIMAGE
LABEL maintainer="Marcin Wielgus <mwielgus@google.com>"

ARG TARGETARCH

COPY --from=builder /src/autoscaler/cluster-autoscaler/cluster-autoscaler-${TARGETARCH} /cluster-autoscaler
WORKDIR /
CMD ["/cluster-autoscaler"]
