#!/usr/bin/env bash
# scripts/checks/d011-05-magnum-e2e.sh -- D-011 item 5: end-to-end Magnum CAPI cluster
# health + OCCM (not crash-looping), by wrapping scripts/tenant-acceptance.sh with timing.
#
# tenant-acceptance verifies an EXISTING tenant cluster end-to-end: P0 health/trustee,
# P1 kubeconfig+nodes+pods, P2 OCCM->Octavia LB serving, P3 cross-tenant isolation.
# Scope note (debated): "cluster CREATION succeeds" is demonstrated transitively -- a
# HEALTHY cluster with a working OCCM LB is a cluster whose create succeeded. A FRESH
# create-verify-teardown is the fuller test and belongs with tenant-cluster-create.sh
# (backlog #5); when that lands, add a --full mode here. Verifying the standing cluster
# is a legitimate item-5 check as written and is fast enough for routine runs.
#
# Isolation (P3) needs a SECOND tenant as the foil. Post-acme-offboard only beta exists,
# so without VR_FOIL_APPCRED the wrapped script HOLDs (exit 14) -- surfaced honestly, not
# hidden. Onboard a foil tenant (or set VR_FOIL_APPCRED) to validate isolation.
#
# Exit (mapping tenant-acceptance 0/11/12/13/14):
#   0 PASS | 11,12 -> FAIL | 13 -> FAIL (CRITICAL isolation) | 14 -> HOLD (precond/no foil)
#   other -> HOLD.  Additive+self-cleaning (tenant-acceptance cleans its lbtest); not disruptive.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=scripts/lib-validate.sh
. "$HERE/../lib-validate.sh"
ID=d011-05-magnum-e2e; vr_begin "$ID"
CLIENT="${VR_TENANT:-beta}"
TA="$HERE/../tenant-acceptance.sh"

[ -x "$TA" ] || [ -f "$TA" ] || { emit "$ID" "$VR_HOLD" "tenant-acceptance.sh not found at $TA"; exit "$VR_HOLD"; }
vr_need kubectl openstack || { emit "$ID" "$VR_HOLD" "missing tool (kubectl/openstack)"; exit "$VR_HOLD"; }

# assemble args: <client> [foil-appcred]
set -- "$CLIENT"
[ -n "${VR_FOIL_APPCRED:-}" ] && set -- "$@" "$VR_FOIL_APPCRED"

T0=$(date +%s)
OUT="$(bash "$TA" "$@" 2>&1)"; RC=$?
T1=$(date +%s); DUR=$((T1 - T0))
printf '%s\n' "$OUT" | sed 's/^/    /'
echo "  tenant-acceptance exit=$RC elapsed=${DUR}s"

case "$RC" in
  0)  emit "$ID" "$VR_PASS" "magnum e2e PASS for '$CLIENT' (health+OCCM+isolation) in ${DUR}s"; exit "$VR_PASS" ;;
  11) emit "$ID" "$VR_FAIL" "P1 kube failed for '$CLIENT' (nodes/pods)"; exit "$VR_FAIL" ;;
  12) emit "$ID" "$VR_FAIL" "P2 OCCM/Octavia LB failed for '$CLIENT'"; exit "$VR_FAIL" ;;
  13) emit "$ID" "$VR_FAIL" "P3 ISOLATION VIOLATION for '$CLIENT' (CRITICAL)"; exit "$VR_FAIL" ;;
  14)
    if printf '%s\n' "$OUT" | grep -qi 'foil app-cred'; then
      emit "$ID" "$VR_HOLD" "no foil tenant for isolation -- onboard a 2nd tenant or set VR_FOIL_APPCRED"
    else
      emit "$ID" "$VR_HOLD" "precondition unmet (cluster/creds/kubectl) for '$CLIENT'"
    fi
    exit "$VR_HOLD" ;;
  *)  emit "$ID" "$VR_HOLD" "tenant-acceptance returned unexpected code $RC"; exit "$VR_HOLD" ;;
esac
