#!/usr/bin/env bash
# tests/phase-02/run-tests.sh
#
# Offline regression for scripts/phase-02-vault-preflight.sh. Drives the REAL
# script's decision/exit logic with juju+jq shims (fakebin/) against generated
# fixtures: one healthy (PROCEED / exit 0) and four single-fault cases the live
# healthy system cannot show -- vault-already-initialized (D), mysql OFFLINE (C),
# a hook failure (E), a down machine (B) -- each must HOLD / exit 1.
#
# Touches NO live infrastructure: fake 'juju' emits fixtures only; fake 'jq'
# mirrors the script's metrics logic in Python. fakebin/ is first on PATH so the
# real juju/jq are shadowed. Runs anywhere with python3 + bash (no real jq needed).
#
# Usage: bash tests/phase-02/run-tests.sh
# Exit: 0 all cases pass | 1 any mismatch
# ASCII + LF.
set -euo pipefail
IFS=$'\n\t'
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARGET="$(cd "$HERE/../../scripts" && pwd)/phase-02-vault-preflight.sh"
BIN="$HERE/fakebin"
[ -f "$TARGET" ] || { echo "FAIL: target not found: $TARGET" >&2; exit 1; }
command -v python3 >/dev/null 2>&1 || { echo "FAIL: python3 required" >&2; exit 1; }
# Re-assert exec bits (the Windows -> git round trip can drop them).
chmod +x "$BIN/juju" "$BIN/jq" 2>/dev/null || true
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
python3 "$HERE/make_fixtures.py" "$WORK" >/dev/null
rc_all=0
run() {
local fix="$1" want="$2" label="$3" rc verdict
set +e
PATH="$BIN:$PATH" FIXTURE="$WORK/$fix" bash "$TARGET" openstack >"$WORK/out" 2>&1
rc=$?
set -e
verdict="$(grep -E '^Summary:' "$WORK/out" | head -1 || true)"
if [ "$rc" -eq "$want" ]; then
printf ' [OK] %-38s exit %s | %s\n' "$label" "$rc" "$verdict"
else
printf ' [XX] %-38s exit %s (WANT %s)\n' "$label" "$rc" "$want"
sed 's/^/ /' "$WORK/out"
rc_all=1
fi
}
echo "=== phase-02-vault-preflight.sh regression ==="
run pass.json 0 "pass (healthy, vault fresh)"
run fail-vault-initialized.json 1 "FAIL D: vault already initialized"
run fail-mysql-degraded.json 1 "FAIL C: mysql unit OFFLINE"
run fail-hook-error.json 1 "FAIL E: hook failure (agent error)"
run fail-machine-down.json 1 "FAIL B: machine down"
if [ "$rc_all" -eq 0 ]; then echo "ALL PASS"; else echo "FAILURES ABOVE"; fi
exit "$rc_all"