#!/usr/bin/env bash
# Verification only (no restarts): served chain vs the Vodafone CA bundle, then smoke with that CA.
# Run from anywhere: uses ./smoke.sh if present, else the newest /data/vodafone-idnow-final*/smoke.sh.
set -uo pipefail
K="/usr/local/bin/k3s kubectl"
step() { printf '\n==> %s  [%s]\n' "$*" "$(date -u +%H:%M:%S)"; }
step "CA bundle from the cluster secret (system roots + Vodafone chain)"
$K -n default get secret customer-ca-bundle -o jsonpath='{.data.ca-certificates\.crt}' | base64 -d > /tmp/ca-bundle.pem
echo "   certs in /tmp/ca-bundle.pem: $(grep -c 'BEGIN CERTIFICATE' /tmp/ca-bundle.pem)  (system roots + 2 Vodafone CAs)"
grep -c 'BEGIN CERTIFICATE' /tmp/ca-bundle.pem | grep -qv '^0$' || { echo "!! empty CA bundle"; exit 1; }
step "verify what is served against that bundle"
for h in api hub; do printf '   %s:443  ' "$h"; openssl s_client -connect 127.0.0.1:443 -servername "$h.idnow.vodafone.de" -CAfile /tmp/ca-bundle.pem </dev/null 2>/dev/null | grep -E 'Verify return code' | sed 's/^ *//'; done
printf '   mdm:8883 '; openssl s_client -connect 127.0.0.1:8883 -servername mdm.idnow.vodafone.de -CAfile /tmp/ca-bundle.pem </dev/null 2>/dev/null | grep -E 'Verify return code' | sed 's/^ *//'
step "smoke with the Vodafone chain as CA"
SMOKE=./smoke.sh; [ -x "$SMOKE" ] || SMOKE=$(ls -d /data/vodafone-idnow-final*/smoke.sh 2>/dev/null | sort -V | tail -1)
echo "   using $SMOKE"; "$SMOKE" --ca /tmp/ca-bundle.pem || true
step "done"
