#!/usr/bin/env bash
# tests/phase-04-internal-cert-san/run-tests.sh -- offline regression for
# scripts/phase-04-internal-cert-san-verify.sh (fake openstack/juju + real jq).
# Run on the jumphost (jq present), same as the other phase tests.
set -euo pipefail
IFS=$'\n\t'
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPTS="$(cd "$HERE/../../scripts" && pwd)"
TARGET="$SCRIPTS/phase-04-internal-cert-san-verify.sh"
BIN="$HERE/fakebin"
command -v jq >/dev/null 2>&1 || { echo "FAIL: jq required (run on the jumphost)" >&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
  local rc
  set +e
  PATH="$BIN:$PATH" OS_AUTH_URL="x" 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-04-internal-cert-san-verify.sh (fake openstack/juju + real jq) ==="
run 0 'Summary: PASS'          "all internal certs carry own IP-SAN"
run 0 'SKIP .* image-stream'   "plain-HTTP image-stream is SKIPPED"
run 1 'NO-SAN .* barbican'     "barbican cert missing own IP-SAN -> HOLD"  BARBICAN_MODE=nosan
run 1 'NO-CERT .* barbican'    "barbican returns no cert -> HOLD"          BARBICAN_MODE=nocert
echo
[ "$rc_all" -eq 0 ] && echo "ALL PASS" || echo "SOME FAILED"
exit "$rc_all"
