#!/usr/bin/env bash
# tests/phase-03-openrc/run-tests.sh -- offline regression for phase-03-admin-openrc.sh
# + unit test of extract_admin_password.py. Fake juju/openstack/openssl; real python3/jq.
set -euo pipefail
IFS=$'\n\t'
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPTS="$(cd "$HERE/../../scripts" && pwd)"
TARGET="$SCRIPTS/phase-03-admin-openrc.sh"
EXTRACT="$SCRIPTS/extract_admin_password.py"
BIN="$HERE/fakebin"
command -v jq >/dev/null 2>&1 || { echo "FAIL: jq required" >&2; exit 1; }
[ -f "$TARGET" ] && [ -f "$EXTRACT" ] || { echo "FAIL: target/helper missing" >&2; exit 1; }
chmod +x "$BIN"/* 2>/dev/null || true
WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
rc_all=0

echo "=== unit: extract_admin_password.py ==="
u() { local want="$1" json="$2" label="$3" got
  got=$(printf '%s' "$json" | python3 "$EXTRACT")
  if [ "$got" = "$want" ]; then printf '  [OK]  %-34s -> %s\n' "$label" "${got:-<empty>}"
  else printf '  [XX]  %-34s -> %s (want %s)\n' "$label" "${got:-<empty>}" "$want"; rc_all=1; fi
}
u "pw1" '{"keystone/0":{"admin-password":"pw1"}}'        "top-level admin-password"
u "pw2" '{"a":{"b":{"password":"pw2"}}}'                  "nested password"
u "pw3" '[{"x":1},{"Stdout":"pw3"}]'                      "list + Stdout"
u ""    '{"keystone/0":{"output":{}}}'                    "no password -> empty"

echo "=== integration: phase-03-admin-openrc.sh ==="
run() {
  local want="$1" re="$2" label="$3"; shift 3
  local rc
  rm -rf "$WORK/vault-init" "$WORK/admin-openrc"
  set +e
  PATH="$BIN:$PATH" HOME="$WORK" CA="$WORK/vault-init/ca.pem" RC="$WORK/admin-openrc" \
    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
}
run 0 'admin project = admin '          "happy: admin scopes"        CORRECT_PROJECT=admin
run 0 'admin project = admin_domain'    "fallback: admin_domain wins" CORRECT_PROJECT=admin_domain
run 1 'no candidate project scoped'     "none scopes -> FATAL"        CORRECT_PROJECT=none
run 1 'password extract failed'         "password empty -> FATAL"     CORRECT_PROJECT=admin PASS_EMPTY=1

echo "=== assert: written openrc is 0600 ==="
rm -rf "$WORK/vault-init" "$WORK/admin-openrc"
PATH="$BIN:$PATH" HOME="$WORK" CA="$WORK/vault-init/ca.pem" RC="$WORK/admin-openrc" \
  CORRECT_PROJECT=admin bash "$TARGET" >/dev/null 2>&1 || true
perm=$(stat -c '%a' "$WORK/admin-openrc" 2>/dev/null || echo "missing")
if [ "$perm" = "600" ]; then echo "  [OK] admin-openrc mode 600"; else echo "  [XX] admin-openrc mode=$perm (want 600)"; rc_all=1; fi

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