#!/bin/bash

# Load pre-built Docker images from the S3 cache, if available.
# Touch marker files so Make skips rebuilding.
#
# Usage: load-cached-images [component...]
#
# The optional component names (calico, node, whisker; default all three) are
# the images the calling block declares as "Build: <x> image" dependencies.
# They matter only when the cache turns up empty. A build without S3
# credentials runs read-only (see .semaphore/s3-cmd), so the producer blocks
# had nowhere to upload their tarballs and there is no cache to hit; the
# declared images are built from source instead. Jobs invoke the *-no-prereqs
# make targets, which never build an image themselves, so without this they
# fail on a "manifest unknown" from Docker.
#
# With credentials a miss is left alone, as before: it means the producer block
# for that image did not run (its change_in trigger did not fire), and a job
# that does not list it as a dependency is not expected to need it.

set -euo pipefail

ARCH=${ARCH:-amd64}
REPO_ROOT=$(git rev-parse --show-toplevel)

REQUESTED=("$@")
if [ ${#REQUESTED[@]} -eq 0 ]; then
    REQUESTED=(calico node whisker)
fi

fetch_tarball() {
    local name=$1
    if [ -n "${CI_ARTIFACT_STORAGE:-}" ]; then
        ( cd /tmp && artifact pull workflow "${name}" )
        return
    fi
    "${REPO_ROOT}/.semaphore/s3-cmd" cp "${S3_WORKFLOW_DIR}/${name}" "/tmp/${name}" 2>/dev/null
}

load_image() {
    local component=$1
    local name=$2
    local s3_path=$3
    shift 3
    local markers=("$@")
    local marker

    # A local image tar (<COMPONENT>_IMAGE_TAR, e.g. CALICO_IMAGE_TAR) is one
    # ArgoCI already put on this machine, read where it lies.
    local local_tar_var
    local_tar_var="$(tr '[:lower:]-' '[:upper:]_' <<<"${component}")_IMAGE_TAR"
    if [ -n "${component}" ] && [ -n "${!local_tar_var:-}" ]; then
        echo "Loading ${name} image from ${!local_tar_var}..."
        docker load -i "${!local_tar_var}"
        touch_markers "${markers[@]}"
        return
    fi

    if ! fetch_tarball "${s3_path}"; then
        # Under ArgoCI the producer has already run, so a miss is a real failure.
        if [ -n "${CI_ARTIFACT_STORAGE:-}" ] && was_requested "$component"; then
            echo "Expected ${name} from ${CI_ARTIFACT_STORAGE}/${s3_path} and it was not there." >&2
            return 1
        fi
        if have_credentials || ! was_requested "$component"; then
            echo "No cached ${name} image found; leaving Make to build it if a target needs it."
            return
        fi
        echo "No cached ${name} image (credential-less build); building it from source."
        build_image "$component" "${markers[@]}"
        return
    fi

    echo "Loading cached ${name} image..."
    local tar_path="/tmp/${s3_path%.zst}"
    zstd -d --rm -o "${tar_path}" "/tmp/${s3_path}"
    docker load -i "${tar_path}"
    rm -f "${tar_path}"
    touch_markers "${markers[@]}"
}

# Make sees the image as built, so it does not build it again.
touch_markers() {
    local marker
    for marker in "$@"; do
        mkdir -p "$(dirname "$marker")"
        touch "$marker"
    done
}

# True when the S3 credentials are present. Mirrors .semaphore/s3-cmd, which
# skips uploads without them — the reason the cache can be empty here.
have_credentials() {
    [[ -n "${CALICO_S3_ACCESS_KEY:-}" && -n "${CALICO_S3_SECRET_KEY:-}" ]]
}

was_requested() {
    local want=$1 component
    for component in "${REQUESTED[@]}"; do
        [[ "$component" == "$want" ]] && return 0
    done
    return 1
}

# Build a component's image through the .image.created marker rule in
# lib.Makefile, the same rule the producer block builds it with.
build_image() {
    local component=$1
    shift

    # node's Dockerfile takes the patched nftables RPMs from a local image. Its
    # build would produce that image from scratch (~20 min); pulling the
    # published one first is much cheaper when it exists.
    if [ "$component" = node ]; then
        "${REPO_ROOT}/.argoci/scripts/load-nft-rpms.sh" "$ARCH"
    fi

    make -C "${REPO_ROOT}" "$@" ARCH="$ARCH"
}

load_image calico  "calico/calico"  "calico-image.tar.zst"  "${REPO_ROOT}/cmd/calico/.image.created-${ARCH}"
load_image node    "calico/node"    "node-image.tar.zst"    "${REPO_ROOT}/node/.image.created-${ARCH}"
load_image whisker "calico/whisker" "whisker-image.tar.zst" "${REPO_ROOT}/whisker/.image.created-${ARCH}"

# The operator image is loaded from the cache but never built from source
# here: its producer block builds it via `make kind-operator-image`, which
# bakes in the kind component refs. On a miss the kind lanes' own targets
# build it.
load_image ""      "calico/operator" "operator-image.tar.zst" "${REPO_ROOT}/operator/.image.created-${ARCH}"

# The third-party images ship as one tarball because no kind lane wants a
# subset. Like the operator they are never built from source here; a miss leaves
# that to the lane's own `make image`.
load_image ""      "third-party"     "third-party-images.tar.zst" \
    "${REPO_ROOT}/third_party/envoy-gateway/.envoy-gateway.created-${ARCH}" \
    "${REPO_ROOT}/third_party/envoy-proxy/.envoy-proxy.created-${ARCH}" \
    "${REPO_ROOT}/third_party/envoy-ratelimit/.envoy-ratelimit.created-${ARCH}" \
    "${REPO_ROOT}/third_party/cni-plugins/.cni-plugins.created-${ARCH}"
