#!/usr/bin/env bash
# tests/phase-04-create/run-tests.sh -- offline regression for phase-04-network-create.sh.
set -euo pipefail
IFS=$'\n\t'
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPTS="$(cd "$HERE/../../scripts" && pwd)"
TARGET="$SCRIPTS/phase-04-network-create.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/net" "$WORK/sub"
  local rc
  set +e
  PATH="$BIN:$PATH" OS_AUTH_URL="x" NET_MARKER="$WORK/net" SUB_MARKER="$WORK/sub" \
    env "$@" bash "$TARGET" >"$WORK/out" 2>&1
  rc=$?; set -e
  if [ "$rc" -eq "$want" ] && grep -qE "$re" "$WORK/out"; then
    printf '  [OK]  %-38s exit %s\n' "$label" "$rc"
  else
    printf '  [XX]  %-38s exit %s (want %s; /%s/)\n' "$label" "$rc" "$want" "$re"
    sed 's/^/        /' "$WORK/out"; rc_all=1
  fi
}
echo "=== phase-04-network-create.sh (fake maas/openstack + real jq) ==="
run 0 'network provider-ext created.*|create complete' "fresh: create net+subnet"
run 0 'SKIP. network provider-ext exists' "idempotent: both present" NET_PRESENT=1 SUB_PRESENT=1
run 1 'GATE FAIL: MAAS provider gateway' "gate fail: wrong gateway" GW=10.12.4.254
run 1 'CONFIRM FAIL' "confirm fail: shared=true" NET_PRESENT=1 SUB_PRESENT=1 BAD_SHARED=1
# DOCFIX-213: MAAS_PROFILE is passed through (fails red if the SUT reverts to hardcoded 'admin':
# stub keyed to EXPECT_PROFILE=vr1-dc0-region would go silent -> GATE FAIL exit 1 != 0).
run 0 'network provider-ext created.*|create complete' "MAAS_PROFILE=vr1-dc0-region passed through" \
  MAAS_PROFILE=vr1-dc0-region EXPECT_PROFILE=vr1-dc0-region
echo
[ "$rc_all" -eq 0 ] && echo "ALL PASS" || echo "SOME FAILED"
exit "$rc_all"
