#!/usr/bin/env bash
set -euo pipefail
repo_root=$(git rev-parse --show-toplevel)
build="$repo_root/modules/ci/image/build.sh"
distribute="$repo_root/modules/ci/image/distribute.sh"
values="$repo_root/modules/ci/arc/runner-values.yaml"
pin="$repo_root/modules/ci/k8s/runner-image-pin.yaml"

# The image reaches the nodes by side-load, not by pull, so three files have to
# agree on one string: the builder that produces the tag, the distributor that
# side-loads it, and the manifest that runs it. A drift between any two of them
# does not fail loudly -- pods go ErrImageNeverPull and jobs queue forever with
# nothing in the CI UI to explain it.
build_image=$(sed -n 's/^IMAGE="\(.*\)"$/\1/p' "$build")
distribute_image=$(sed -n 's/^image=${ARC_RUNNER_IMAGE:-\(.*\)}$/\1/p' "$distribute")
values_image=$(sed -n 's/^ *image: \(.*\)$/\1/p' "$values")

[[ -n "$build_image" ]] || { printf 'runner-image: no IMAGE in build.sh\n' >&2; exit 1; }
[[ "$build_image" == "$distribute_image" ]] || {
  printf 'runner-image: build.sh (%s) and distribute.sh (%s) disagree\n' \
    "$build_image" "$distribute_image" >&2
  exit 1
}
[[ "$values_image" == "$build_image" ]] || {
  printf 'runner-image: runner-values.yaml (%s) does not match build.sh (%s)\n' \
    "$values_image" "$build_image" >&2
  exit 1
}

# The GC pin only protects the image it names. A pin on a stale tag leaves the
# real runner image collectable, and nothing about that looks wrong until a job
# lands on the node that lost it.
pin_image=$(sed -n 's/^ *image: \(.*\)$/\1/p' "$pin")
[[ "$pin_image" == "$build_image" ]] || {
  printf 'runner-image: runner-image-pin.yaml (%s) does not match build.sh (%s)\n' \
    "$pin_image" "$build_image" >&2
  exit 1
}
grep -qE '^ *imagePullPolicy: Never$' "$pin" || {
  printf 'runner-image: runner-image-pin.yaml must pin imagePullPolicy: Never\n' >&2
  exit 1
}

# A pull policy other than Never would retry a pull that can never succeed: the
# cluster has no registries.yaml and the GHCR packages are private with no
# imagePullSecret, so the tag is an identifier and not a reachable reference.
grep -qE '^ *imagePullPolicy: Never$' "$values" || {
  printf 'runner-image: runner-values.yaml must pin imagePullPolicy: Never\n' >&2
  exit 1
}

# The installer must repair a missing side-load before installing the chart.
grep -qF 'image/distribute.sh' "$repo_root/modules/ci/install-arc.sh" || {
  printf 'runner-image: install-arc.sh never runs image/distribute.sh\n' >&2
  exit 1
}

printf 'runner image tag/pull-policy/side-load wiring: PASS (%s)\n' "$build_image"
