#!/usr/bin/env bash
# tests/phase-06-bootstrap/run-tests.sh -- offline regression for phase-06-bootstrap.sh.
set -euo pipefail
IFS=$'\n\t'
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPTS="$(cd "$HERE/../../scripts" && pwd)"
TARGET="$SCRIPTS/phase-06-bootstrap.sh"
BIN="$HERE/fakebin"
command -v jq >/dev/null 2>&1 || { echo "FAIL: jq required" >&2; exit 1; }
[ -f "$TARGET" ] || { echo "FAIL: target missing" >&2; exit 1; }
chmod +x "$BIN"/* 2>/dev/null || true
WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
rc_all=0
run() {
  local want="$1" re="$2" label="$3"; shift 3
  rm -f "$WORK/img.marker" "$WORK/noble-server-cloudimg-amd64.img"
  local rc
  set +e
  PATH="$BIN:$PATH" HOME="$WORK" OS_AUTH_URL=x OS_USERNAME=admin OS_USER_DOMAIN_NAME=admin_domain \
    MK_IMAGE="$WORK/img.marker" POLL_TRIES=3 POLL_SLEEP=0 FAKE_EXP=aaaa FAKE_SHA=aaaa \
    env "$@" bash "$TARGET" >"$WORK/out" 2>&1
  rc=$?; set -e
  if [ "$rc" -eq "$want" ] && grep -qE "$re" "$WORK/out"; then
    printf '  [OK]  %-40s exit %s\n' "$label" "$rc"
  else
    printf '  [XX]  %-40s exit %s (want %s; /%s/)\n' "$label" "$rc" "$want" "$re"
    sed 's/^/        /' "$WORK/out"; rc_all=1
  fi
}
echo "=== phase-06-bootstrap.sh (fake openstack/curl/wget/sha256sum + real jq) ==="
run 0 'bootstrap complete'                 "fresh: create everything + image active"
run 0 'SKIP. image ubuntu-24.04-noble exists' "idempotent: all present" \
      DOMAIN_PRESENT=1 PROJECT_PRESENT=1 ROLES_PRESENT=1 FLAVORS_PRESENT=1 IMG_PRESENT=1
run 1 'checksum mismatch'                  "checksum mismatch -> abort"  FAKE_SHA=bbbb
run 1 'no published checksum'              "no published checksum -> abort" NO_PUBLISHED=1
run 1 'not active after'                   "poll never active -> abort"  POLL_FAIL=1
run 2 'OS_AUTH_URL unset'                  "precondition: no auth -> exit 2" OS_AUTH_URL=
echo
# PRESTAGE handling: the 'staged valid' case needs the SRC file present BEFORE the run.
# Re-run that one case explicitly with pre-staged file (the generic run() rm's it).
echo "=== explicit: staged-present (SRC pre-created, matching checksum) ==="
rm -f "$WORK/img.marker"; : > "$WORK/noble-server-cloudimg-amd64.img"
set +e
PATH="$BIN:$PATH" HOME="$WORK" OS_AUTH_URL=x OS_USERNAME=admin OS_USER_DOMAIN_NAME=admin_domain \
  MK_IMAGE="$WORK/img.marker" POLL_TRIES=3 POLL_SLEEP=0 FAKE_EXP=aaaa FAKE_SHA=aaaa \
  bash "$TARGET" >"$WORK/out2" 2>&1
rc=$?; set -e
if [ "$rc" -eq 0 ] && grep -q 'skipping download' "$WORK/out2"; then echo "  [OK]  staged-present skips download   exit 0"; else echo "  [XX]  staged-present  exit $rc"; sed 's/^/        /' "$WORK/out2"; rc_all=1; fi
echo
[ "$rc_all" -eq 0 ] && echo "ALL PASS" || echo "SOME FAILED"
exit "$rc_all"
