#!/bin/bash
# Bundle or push the images AF analys needs for chart 5.2.2.
#
#   bundle_images.sh pull <outdir>            docker.hops.works -> <outdir>/<n>.tar (linux/amd64)
#   bundle_images.sh push <outdir> <registry> [regex]
#                                             <outdir>/*.tar  -> <registry>/<path>:<tag>,
#                                             only the images whose <path>:<tag> matches regex
#
# images-5.2.2.txt holds paths relative to the registry, taken from
# `helm template` of chart 5.2.2 with AF's values.analys.yaml + values.airgap.yaml:
# every pod image, plus the ones only named in config (Kafka CR, preset base
# images, terminal/jupyter/git/buildkit, serving sidecars).
# Already-saved tarballs are skipped, so a broken run resumes.
set -euo pipefail

mode=${1:?pull|push}
out=${2:?outdir}
list=$(dirname "$0")/images-5.2.2.txt
src=docker.hops.works

mkdir -p "$out"
n=0
handled=0
fail=0
while read -r img; do
    n=$((n + 1))
    tar="$out/$(printf '%03d' "$n")-$(echo "$img" | tr '/:' '__').tar"
    case "$mode" in
        pull)
            if [[ -s "$tar" ]]; then
                continue
            fi
            echo "[$n] $src/$img"
            handled=$((handled + 1))
            if ! crane pull --platform linux/amd64 "$src/$img" "$tar.part"; then
                echo "FAILED $img" >&2
                rm -f "$tar.part"
                fail=$((fail + 1))
                continue
            fi
            mv "$tar.part" "$tar"
            ;;
        push)
            dst=${3:?registry, e.g. ocp4-quay.arbetsformedlingen.se/<org>}
            if [[ -n "${4:-}" ]] && ! grep -qE -- "$4" <<< "$img"; then
                continue
            fi
            echo "[$n] $dst/$img"
            handled=$((handled + 1))
            if ! crane push "$tar" "$dst/$img"; then
                echo "FAILED $img" >&2
                fail=$((fail + 1))
            fi
            ;;
        *)
            echo "unknown mode $mode" >&2
            exit 1
            ;;
    esac
done < "$list"

echo "done: $handled of $n images, $fail failed"
[[ $fail -eq 0 ]]
