#!/usr/bin/env bash
# Behavior regression for phase-00-teardown.sh. Fake juju + fake maas + real jq.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPT="$(cd "$HERE/../../scripts" && pwd)/phase-00-teardown.sh"
BIN="$HERE/fakebin"; FIX="$HERE/fix"
chmod +x "$BIN"/* 2>/dev/null || true
command -v jq >/dev/null || { echo "FAIL: jq required"; exit 1; }
python3 "$HERE/make_fixtures.py" >/dev/null
rc_all=0; OUT="$(mktemp)"
run() { local want="$1" label="$2" s="$3"; shift 3
PATH="$BIN:$PATH" FIX_MACHINES="$FIX/${s}_machines.json" FIX_MODELS="$FIX/${s}_models.json" \
bash "$SCRIPT" "$@" >"$OUT" 2>&1; local rc=$?
if [ "$rc" -ne "$want" ]; then printf ' [XX] %-44s exit %s (want %s)\n' "$label" "$rc" "$want"; sed 's/^/ /' "$OUT"; rc_all=1; return 1; fi
printf ' [ok] %-44s exit %s\n' "$label" "$rc"; return 0; }
has() { grep -qE "$1" "$OUT" || { printf ' MISS /%s/\n' "$1"; rc_all=1; }; }
absent(){ grep -qE "$1" "$OUT" && { printf ' LEAK /%s/\n' "$1"; rc_all=1; } || true; }
# assert NONE of the substrate system_ids appear on a "DO:" line
no_substrate_do(){ if grep -E '^\s*DO:' "$OUT" | grep -qE '88fkyf|mfewpp|rkd3da'; then printf ' SUBSTRATE in a DO line!\n'; rc_all=1; fi; }
echo "=== phase-00-teardown.sh -- model destroy + orphan delete, substrate-protected ==="
run 0 "audit (dry-run): plan + protections" live
has 'PROTECTED substrate'
has 'juju = 88fkyf .*PROTECTED'; has 'lxd = mfewpp .*PROTECTED'; has 'tailscale = rkd3da .*PROTECTED'
has 'openstack0 = 6xey8x'; has 'openstack3 = htbft7'
has 'capi-mgmt = cffxxg .*DELETE'
has "model 'openstack' is PRESENT"
has 'OK \(dryrun\)'
absent '^\s*DO:'
run 0 "apply --no-prompt: destroy + delete orphan" live --apply --no-prompt
has 'DO: destroy model openstack'
has 'DO: delete orphan capi-mgmt'
has 'VERIFY 3/3'
has 'PROTECTED tailscale -> Deployed \(unchanged\)'
has 'OK \(apply\)'
no_substrate_do
run 1 "safety: a host missing -> ABORT" hostmissing --apply --no-prompt
has 'openstack2: not found in MAAS'
has 'ABORT'
absent 'DO: destroy model'
run 0 "idempotent: model already gone -> skip destroy" modelgone --apply --no-prompt
has "model 'openstack' not present"
absent 'DO: destroy model openstack'
has 'DO: delete orphan capi-mgmt'
has 'OK \(apply\)'
echo
[ "$rc_all" -eq 0 ] && echo "ALL PASS" || echo "SOME FAILED"
rm -f "$OUT"; exit "$rc_all"