ARG ALPINE_VERSION=3.16
ARG PYTHON_VERSION=3.11


#
# Builder: AWS CLI v2.x
#
FROM --platform=$TARGETPLATFORM python:${PYTHON_VERSION}-alpine${ALPINE_VERSION} as builder-aws
ARG AWS_CLI_VERSION

RUN --mount=type=cache,target=/var/cache/apk apk add git unzip groff build-base libffi-dev cmake
RUN git clone --single-branch --depth 1 -b ${AWS_CLI_VERSION} https://github.com/aws/aws-cli.git

WORKDIR aws-cli
RUN sed -i'' 's/PyInstaller.*/PyInstaller==5.2/g' requirements-build.txt
RUN python -m venv venv
RUN . venv/bin/activate
RUN scripts/installers/make-exe
RUN unzip -q dist/awscli-exe.zip
RUN aws/install --bin-dir /aws-cli-bin
RUN /aws-cli-bin/aws --version

RUN rm -rf /usr/local/aws-cli/v2/current/dist/aws_completer /usr/local/aws-cli/v2/current/dist/awscli/data/ac.index /usr/local/aws-cli/v2/current/dist/awscli/examples
RUN find /usr/local/aws-cli/v2/current/dist/awscli/botocore/data -name examples-1.json -delete

#
# Builder: regctl
#
FROM --platform=$TARGETPLATFORM python:${PYTHON_VERSION}-alpine${ALPINE_VERSION} as builder-regctl
ARG TARGETARCH
ARG REGCTL_VERSION

RUN --mount=type=cache,target=/var/cache/apk apk add curl

# Install regclient, Notice to support aarch64 and amd64 architectures I am passing TARGETARCH 
# into the URL to pull the correct binary.
RUN mkdir -p /opt/regclient/bin
RUN curl -sL https://github.com/regclient/regclient/releases/download/v${REGCTL_VERSION}/regctl-linux-${TARGETARCH} > /opt/regclient/bin/regctl
RUN chmod 755 /opt/regclient/bin/regctl

#
# Builder: kubectl
#
FROM --platform=$TARGETPLATFORM python:${PYTHON_VERSION}-alpine${ALPINE_VERSION} as builder-kubectl
ARG TARGETPLATFORM
ARG KUBECTL_VERSION

RUN --mount=type=cache,target=/var/cache/apk apk add curl

# Install kubectl
RUN mkdir -p /opt/kubectl/bin
RUN curl -s -L -o /opt/kubectl/bin/kubectl "https://dl.k8s.io/release/v${KUBECTL_VERSION}/bin/${TARGETPLATFORM}/kubectl"
RUN chmod 755 /opt/kubectl/bin/kubectl


#
# Runtime Container
#
FROM --platform=$TARGETPLATFORM python:${PYTHON_VERSION}-alpine${ALPINE_VERSION}

ENV SYNC_USER=datasync
ENV SYNC_HOME=/datasync


RUN \
    # Add other container dependencies
    apk add git --no-cache \
    git \
    openssh-client \
    curl \
    ca-certificates \
    jq \
    openssl && \
    \
    # Add a non-superuser container user
    adduser -D -h ${SYNC_HOME} -g ${SYNC_USER} ${SYNC_USER} 

# Copy tools into runtime container from other multistage build steps
COPY --from=builder-kubectl /opt/kubectl/bin/kubectl /usr/local/bin/
COPY --from=builder-regctl /opt/regclient/bin/regctl /usr/local/bin/
COPY --from=builder-aws /usr/local/aws-cli/ /usr/local/aws-cli/
COPY --from=builder-aws /aws-cli-bin/ /opt/aws-cli/
COPY aws /usr/local/bin/

USER ${SYNC_USER}
WORKDIR ${SYNC_HOME}

CMD ["/bin/ash"]
