# Stage 1: Define a minimal stage to extract the 'uv' binary
# This is a multi-stage build to use uv for dependency management and is necessary to ensure the the image version we pull is for the right architecture.
# This is automatically set by the buildx builder. when using --platoform linux/amd64,linux/arm64 argument and then
# using FROM in the Dockerfile.
FROM ghcr.io/astral-sh/uv:0.4.0 AS uv_extractor


# Stage 2: The main application build stage
FROM python:3.12-slim

ARG TARGETARCH

##
## Install kubectl and dependencies.
##
ENV KUBE_LATEST_VERSION="v1.21.3"
ENV HELM_VERSION="v3.6.2" \
    VIRTUAL_ENV="/app/.venv" \
    PATH="/app/.venv/bin:$PATH"


RUN apt-get update \
    && apt-get install wget ca-certificates bash git git-crypt -y --no-install-recommends \
    # Download kubectl
    && wget -q https://storage.googleapis.com/kubernetes-release/release/${KUBE_LATEST_VERSION}/bin/linux/${TARGETARCH}/kubectl -O /usr/local/bin/kubectl \
    && chmod +x /usr/local/bin/kubectl \
    \
    # Download helm
    && wget -q https://get.helm.sh/helm-${HELM_VERSION}-linux-${TARGETARCH}.tar.gz -O - | tar -xzO linux-${TARGETARCH}/helm > /usr/local/bin/helm \
    && chmod +x /usr/local/bin/helm \
    \
    # Install helm-secrets plugin
    && helm plugin install https://github.com/jkroepke/helm-secrets --version v4.2.2 \
    \
    # Download sops
    && wget -q https://github.com/mozilla/sops/releases/download/v3.7.3/sops-v3.7.3.linux.${TARGETARCH} -O /usr/local/bin/sops \
    && chmod +x  /usr/local/bin/sops \
    \
    && apt-get clean \
    && apt-get -y autoremove \
    && rm -rf /var/lib/apt/lists/* \
    && rm -rf /var/cache/apt/

ENV SHELL=/bin/bash

##
## Install dependencies and copy GitOps server.
##
WORKDIR /app



# Copy the uv binary from the uv image to the final image.
COPY --from=uv_extractor /uv /bin/uv
COPY --link=true pyproject.toml uv.lock /app/
RUN --mount=type=cache,target=/root/.cache/ \
    (uv sync --frozen --no-install-project --extra server || uv sync --frozen --no-install-project --extra server)
# Install dependencies
RUN git config --global advice.detachedHead false

COPY cluster.key /app/
COPY gitops /app/gitops/
COPY gitops_server /app/gitops_server

ENV GIT_CRYPT_KEY_FILE=/app/cluster.key
ENV PYTHONPATH="$PYTHONPATH:/app"
ENV ACCESS_LOG=""

CMD ["uvicorn", "--host", "0.0.0.0", "--port", "8000", "gitops_server.main:app"]