#!/usr/bin/env bash
# tests/phase-06-k8s-bootstrap/run-tests.sh -- offline regression for
# phase-06-k8s-bootstrap.sh. Fake ssh; real bash.
set -euo pipefail
IFS=$'\n\t'
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPTS="$(cd "$HERE/../../scripts" && pwd)"
TARGET="$SCRIPTS/phase-06-k8s-bootstrap.sh"
BIN="$HERE/fakebin"
[ -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

# baseline fixtures: env file + fake ssh key
mkenv() { printf 'MGMT_FIP=%s\nMGMT_TENANT_IP=%s\n' "${1:-10.12.7.222}" "${2:-10.20.0.207}" > "$WORK/net.env"; }
: > "$WORK/id_key"

run() {  # want_rc  regex  label  [extra env assignments...]
  local want="$1" re="$2" label="$3"; shift 3
  local rc
  set +e
  PATH="$BIN:$PATH" HOME="$WORK" ENVFILE="$WORK/net.env" SSH_KEY="$WORK/id_key" \
    PROBE_TIMEOUT=1 BOOT_TIMEOUT=1m READY_TIMEOUT=1m \
    env "$@" bash "$TARGET" >"$WORK/out" 2>&1
  rc=$?
  set -e
  if [ "$rc" -eq "$want" ] && grep -qE "$re" "$WORK/out"; then
    printf '  [OK]  %-46s exit %s\n' "$label" "$rc"
  else
    printf '  [XX]  %-46s exit %s (want %s; /%s/)\n' "$label" "$rc" "$want" "$re"
    sed 's/^/        /' "$WORK/out"; rc_all=1
  fi
}

echo "=== phase-06-k8s-bootstrap.sh ==="
mkenv
run 0 'GATE 1 passed'                             "happy path (literal keystone + bootstrap)"
run 0 'Keystone public endpoint: 10.12.4.50:5000' "keystone = as-run literal default (no discovery)"
run 0 'bootstrapped and ready'                    "6.4 reaches ready"
run 0 'Keystone public endpoint: 1.2.3.4:5000'    "KEYSTONE_HOSTPORT override honored"         KEYSTONE_HOSTPORT=1.2.3.4:5000
run 1 'VM egress probe did not pass'              "GATE 1 VIP fail -> exit 1"                  VIP_FAIL=1
run 1 'VM egress probe did not pass'              "GATE 1 NET fail -> exit 1"                  NET_FAIL=1
run 1 'did not reach ready'                       "6.4 bootstrap fail -> exit 1"               BOOT_FAIL=1

# preconditions
run 2 'not found' "precondition: no ENVFILE -> exit 2" ENVFILE="$WORK/nope.env"
mkenv "" ""; : > "$WORK/net.env"   # empty env file (no MGMT_FIP)
run 2 'MGMT_FIP unset' "precondition: MGMT_FIP unset -> exit 2"
mkenv
run 2 'ssh key' "precondition: missing ssh key -> exit 2" SSH_KEY="$WORK/nokey"

# as-run fidelity: the script must NOT dynamically discover Keystone (uses the literal)
set +e
PATH="$BIN:$PATH" HOME="$WORK" ENVFILE="$WORK/net.env" SSH_KEY="$WORK/id_key" \
  PROBE_TIMEOUT=1 BOOT_TIMEOUT=1m READY_TIMEOUT=1m bash "$TARGET" >"$WORK/fid" 2>&1
set -e
if grep -qiE 'discovered|endpoint list' "$WORK/fid"; then
  printf '  [XX]  %-46s (performed discovery; must use as-run literal)\n' "fidelity: no dynamic discovery"; rc_all=1
else
  printf '  [OK]  %-46s\n' "fidelity: no dynamic discovery (as-run literal)"
fi

echo
[ "$rc_all" -eq 0 ] && echo "ALL PASS" || echo "SOME FAILED"
exit "$rc_all"
