#!/usr/bin/env bash
# Second half of the TLS swap: restarts + verification. Run from the current bundle dir (needs ./smoke.sh).
set -uo pipefail
K="/usr/local/bin/k3s kubectl"
step() { printf '\n==> %s  [%s]\n' "$*" "$(date -u +%H:%M:%S)"; }
step "secret now carries"
$K -n default get secret emteria-tls -o jsonpath='{.data.tls\.crt}' | base64 -d | openssl x509 -noout -issuer -enddate
echo "   certs in the served chain: $($K -n default get secret emteria-tls -o jsonpath='{.data.tls\.crt}' | base64 -d | grep -c 'BEGIN CERTIFICATE')"
step "restart ALL .NET services (every one mounts the ca-bundle via subPath, which never picks up a Secret update) and the mdm broker (reads PEM at startup)"
# Lesson from 2026-09-29: restarting only website left productmanager/storagemanager with the old CA bundle ->
# their token call to https://api.<domain> failed with UntrustedRoot -> hub got 422 on products/files.
$K -n default rollout restart deployment daemonset/mdm
for d in $($K -n default get deployment -o name); do $K -n default rollout status "$d" --timeout=300s; done
$K -n default rollout status daemonset/mdm --timeout=300s
step "what is served now (ingress-nginx reloads live)"
for h in api hub mdm; do printf '   %s:443   ' "$h"; openssl s_client -connect 127.0.0.1:443 -servername "$h.idnow.vodafone.de" </dev/null 2>/dev/null | openssl x509 -noout -issuer -enddate | tr '\n' ' '; echo; done
printf '   mdm:8883  '; openssl s_client -connect 127.0.0.1:8883 -servername mdm.idnow.vodafone.de </dev/null 2>/dev/null | openssl x509 -noout -issuer -enddate | tr '\n' ' '; echo
echo "   chain depth served on 443: $(openssl s_client -connect 127.0.0.1:443 -servername api.idnow.vodafone.de -showcerts </dev/null 2>/dev/null | grep -c 'BEGIN CERTIFICATE')"
echo "   verify against the Vodafone chain (from the ca-bundle secret):"
$K -n default get secret customer-ca-bundle -o jsonpath='{.data.ca-certificates\.crt}' | base64 -d > /tmp/ca-bundle.pem
for p in 443 8883; do printf '   port %s: ' "$p"; openssl s_client -connect 127.0.0.1:$p -servername mdm.idnow.vodafone.de -CAfile /tmp/ca-bundle.pem </dev/null 2>/dev/null | grep -E 'Verify return code' | sed 's/^ *//'; done
step "applications (want 14/14 Synced Healthy)"
sleep 30; $K -n argocd get applications
step "smoke with the Vodafone chain as CA (dns.* rows and mdm.cert-match must PASS now)"
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"
