#!/usr/bin/env bash
# tests/phase-03/run-tests.sh -- offline regression for phase-03 Step 3.1 verify.
# Unit-tests phase03_accept_walk.py against fixtures; behavior-tests phase-03-core-verify.sh
# with juju+jq shims (incl an injected haproxy-DOWN case). No live infra. python3 + bash only.
set -euo pipefail
IFS=$'\n\t'
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPTS="$(cd "$HERE/../../scripts" && pwd)"
TARGET="$SCRIPTS/phase-03-core-verify.sh"
WALK="$SCRIPTS/phase03_accept_walk.py"
BIN="$HERE/fakebin"
command -v python3 >/dev/null 2>&1 || { echo "FAIL: python3 required" >&2; exit 1; }
[ -f "$TARGET" ] && [ -f "$WALK" ] || { echo "FAIL: target/helper missing" >&2; exit 1; }
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

echo "=== unit: phase03_accept_walk.py ==="
walk_case() {
  local fix="$1" want="$2" label="$3" rc
  set +e; python3 "$WALK" <"$WORK/$fix" >/dev/null 2>&1; rc=$?; set -e
  if [ "$rc" -eq "$want" ]; then printf '  [OK]  %-42s exit %s\n' "$label" "$rc"
  else printf '  [XX]  %-42s exit %s (WANT %s)\n' "$label" "$rc" "$want"; rc_all=1; fi
}
walk_case pass.json        0 "accept-walk pass (octavia+glance-ss only)"
walk_case fail-accept.json 1 "accept-walk fail (unexpected blocked)"

echo "=== integration: phase-03-core-verify.sh (shims) ==="
run() {
  local fix="$1" want="$2" label="$3"; shift 3
  local rc v
  set +e
  PATH="$BIN:$PATH" FIXTURE="$WORK/$fix" env "$@" bash "$TARGET" openstack >"$WORK/out" 2>&1
  rc=$?; set -e
  v="$(grep -E '^Summary:' "$WORK/out" | head -1 || true)"
  if [ "$rc" -eq "$want" ]; then printf '  [OK]  %-42s exit %s | %s\n' "$label" "$rc" "$v"
  else printf '  [XX]  %-42s exit %s (WANT %s)\n' "$label" "$rc" "$want"; sed 's/^/        /' "$WORK/out"; rc_all=1; fi
}
run pass.json        0 "settled + haproxy clean"
run fail-accept.json 1 "unexpected non-active/idle unit"
run pass.json        1 "haproxy backend DOWN" HAPROXY_DOWN=nova-cloud-controller/0

[ "$rc_all" -eq 0 ] && echo "ALL PASS" || echo "FAILURES ABOVE"
exit "$rc_all"
