#!/usr/bin/env bash
# Capture complete cluster exports and atomically preserve the protection union.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
OUT="${OUT:-${HOME}/.local/state/railiance-platform/live-images/all.txt}"
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
sources=()
capture() {
  local context="$1" file="$tmpdir/export-${#sources[@]}.txt"
  local args=()
  if [[ -n "$context" ]]; then args=(--context "$context"); fi
  kubectl "${args[@]}" --request-timeout=30s get pods -A \
    -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.image}{"\n"}{end}{range .spec.initContainers[*]}{.image}{"\n"}{end}{range .spec.ephemeralContainers[*]}{.image}{"\n"}{end}{end}' > "$file"
  sources+=(--source "$file")
}
if [[ -z "${CONTEXTS:-}" ]]; then
  capture ""
else
  for context in $CONTEXTS; do capture "$context"; done
fi
for file in ${EXTRA_LIVE_FILES:-}; do sources+=(--source "$file"); done
python3 "$ROOT/scripts/refresh_live_images.py" --output "$OUT" "${sources[@]}"
