#!/usr/bin/env bash
# tests/phase-05-amphora/run-tests.sh -- offline logic regression for
# scripts/phase-05-amphora-pipeline.sh. Drives the REAL script through fake
# juju/openstack/curl/wget/sha256sum shims (the retrofit "builds" by touching a marker,
# so the confirm step sees the amphora appear). Tests branching + gates, NOT real I/O.
# No live infra. Needs python3-free bash only.
set -euo pipefail
IFS=$'\n\t'
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPTS="$(cd "$HERE/../../scripts" && pwd)"
TARGET="$SCRIPTS/phase-05-amphora-pipeline.sh"
BIN="$HERE/fakebin"
[ -f "$TARGET" ] || { echo "FAIL: target missing: $TARGET" >&2; exit 1; }
chmod +x "$BIN"/* 2>/dev/null || true

WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
rc_all=0

# run <want_rc> <stdout_regex_must_match> <label> KEY=VAL ...
run() {
  local want="$1" wantout="$2" label="$3"; shift 3
  local rc
  rm -f "$WORK/marker"; rm -rf "$WORK/stage"
  set +e
  PATH="$BIN:$PATH" OS_AUTH_URL="http://fake:5000/v3" HOME="$WORK" \
    MARKER="$WORK/marker" STAGE="$WORK/stage" RETROFIT_WAIT="1m" \
    env "$@" bash "$TARGET" >"$WORK/out" 2>&1
  rc=$?
  set -e
  if [ "$rc" -eq "$want" ] && grep -qE "$wantout" "$WORK/out"; then
    printf '  [OK]  %-40s exit %s\n' "$label" "$rc"
  else
    printf '  [XX]  %-40s exit %s (want %s; /%s/)\n' "$label" "$rc" "$want" "$wantout"
    sed 's/^/        /' "$WORK/out"; rc_all=1
  fi
}

echo "=== phase-05-amphora-pipeline.sh (fake juju/openstack/curl/wget/sha256sum) ==="

# config gate aborts
run 1 'GATE FAIL: .*image-format'  "config fail: image-format qcow2"  CFG_IMGFMT="qcow2"
run 1 'GATE FAIL: amp-image-tag'   "config fail: amp-image-tag mismatch" CFG_OTAG="octavia-amphora-x"

# idempotent skip (amphora already tagged+active)
run 0 'SKIP. image already tagged' "idempotent: amphora present -> skip" AMPH_PRESENT="1"

# fresh full path: no base, no amphora; checksum matches; retrofit builds -> confirm
run 0 'checksum verified' "fresh: download+verify+upload+retrofit" \
  BASE_PRESENT="0" PUB_SHA="abc123" SHIM_SHA="abc123"

# retrofit-only: base present, no amphora; skip download; retrofit -> confirm
run 0 'D-021 complete' "retrofit-only: base present" BASE_PRESENT="1"

# checksum mismatch aborts before upload/build
run 1 'checksum mismatch' "fresh: checksum mismatch -> abort" \
  BASE_PRESENT="0" PUB_SHA="aaaa" SHIM_SHA="bbbb"

# extra assertion: retrofit-only must NOT download
echo "--- assert retrofit-only path does not download ---"
rm -f "$WORK/marker"; rm -rf "$WORK/stage"
PATH="$BIN:$PATH" OS_AUTH_URL="x" HOME="$WORK" MARKER="$WORK/marker" STAGE="$WORK/stage" \
  BASE_PRESENT="1" bash "$TARGET" >"$WORK/o2" 2>&1 || true
if grep -q 'downloading' "$WORK/o2"; then echo "  [XX] retrofit-only unexpectedly downloaded"; rc_all=1
else echo "  [OK] retrofit-only skipped the download"; fi

echo
if [ "$rc_all" -eq 0 ]; then echo "ALL PASS"; else echo "SOME FAILED"; fi
exit "$rc_all"
