#!/usr/bin/env bash
# tests/phase-06-net-setup/run-tests.sh -- offline regression for phase-06-net-setup.sh.
set -euo pipefail
IFS=$'\n\t'
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPTS="$(cd "$HERE/../../scripts" && pwd)"
TARGET="$SCRIPTS/phase-06-net-setup.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
: > "$WORK/key.pub"
rc_all=0
run() {
  local want="$1" re="$2" label="$3"; shift 3
  rm -f "$WORK/sg.marker" "$WORK/gw.marker" "$WORK/net.marker"
  local rc
  set +e
  PATH="$BIN:$PATH" HOME="$WORK" OS_AUTH_URL=x PUBKEY="$WORK/key.pub" \
    MK_SG="$WORK/sg.marker" MK_GW="$WORK/gw.marker" MK_NET="$WORK/net.marker" \
    EXT_NAME=provider-ext ROUTER_POLL_TRIES=2 ROUTER_POLL_SLEEP=0 \
    env "$@" bash "$TARGET" >"$WORK/out" 2>&1
  rc=$?; set -e
  if [ "$rc" -eq "$want" ] && grep -qE "$re" "$WORK/out"; then
    printf '  [OK]  %-42s exit %s\n' "$label" "$rc"
  else
    printf '  [XX]  %-42s exit %s (want %s; /%s/)\n' "$label" "$rc" "$want" "$re"
    sed 's/^/        /' "$WORK/out"; rc_all=1
  fi
}
echo "=== phase-06-net-setup.sh (fake openstack + real jq) ==="
run 0 'net-setup complete'              "fresh: create keypair/sg/rules/net/subnet/router"
run 0 'SKIP. keypair capi-mgmt-key'     "idempotent: all present" \
      KEYPAIR_PRESENT=1 SG_PRESENT=1 RULES_PRESENT=1 NET_PRESENT=1 SUBNET_PRESENT=1 ROUTER_PRESENT=1 GW_PRESENT=1
run 1 'GATE FAIL: router'               "router not ACTIVE -> gate fail" ROUTER_STATUS=BUILD
run 2 'pubkey .* not found'             "fresh keypair, missing pubkey -> exit 2" PUBKEY=/nonexistent/x.pub
run 2 'OS_AUTH_URL unset'               "precondition: no auth -> exit 2" OS_AUTH_URL=
echo
[ "$rc_all" -eq 0 ] && echo "ALL PASS" || echo "SOME FAILED"
exit "$rc_all"
