#!/usr/bin/env bash
# T91 — mTLS Passthrough + connectionPool on both DRs (docs/istio/egress/mtls-passthrough-connectionpool)
# Istio 1.30.0 sidecar mode / k8s 1.30.6. Registry domain on this cluster: homelab.local
# (istiod --domain homelab.local — adapt DR/VS k8s-service hosts to what
#  `istioctl proxy-config cluster <pod>` shows on YOUR cluster.)
# External target: pre-existing mock.istio-verify-ext (mendhak/http-https-echo, NO sidecar,
# self-signed HTTPS :443). Reproduced here as executed on 2026-07-05.
set -euo pipefail
D=$(cd "$(dirname "$0")" && pwd)
NS=istio-vt-t91

# ---------- 1. workloads: ns + injected client + dedicated gateway ----------
kubectl apply -f "$D/workloads.yaml"
kubectl -n "$NS" rollout status deploy/t91-egress --timeout=180s
kubectl -n "$NS" wait --for=condition=Ready pod/client --timeout=180s

# ---------- 2. negative: tls.mode "tcp" does not exist (expect rejection) ----------
kubectl apply -f "$D/dr-mode-tcp-invalid.yaml" && echo "UNEXPECTED: accepted" || echo "OK: rejected"

# ---------- 3. wiring: SE / Gateway(TLS+ISTIO_MUTUAL) / DR1(pool 111) / DR2(no tls, pool 222) / VS(tls+tcp) ----------
kubectl apply -f "$D/wiring.yaml"; sleep 8

# ---------- 4. E2E + path proofs ----------
# 240.240.34.91 = dummy non-registry IP; sidecar intercepts and routes by SNI (VS tls leg-1)
CURL="kubectl -n $NS exec client -c curl -- curl -sk --resolve api.partner.example:443:240.240.34.91 https://api.partner.example/"
$CURL -o /dev/null -w 'http=%{http_code} ssl_verify=%{ssl_verify_result}\n'   # expect 200, 18(self-signed seen e2e)
$CURL | grep -E '"ip"|servername|clientCertificate'                            # peer=gateway pod IP, inner SNI intact
kubectl -n "$NS" logs deploy/t91-egress --tail=5 | grep -o 'outbound|443||api.partner.example.*'

# ---------- 5. pool placement proofs ----------
# hop1 -> CLIENT sidecar cluster (expect max=111, ISTIO_MUTUAL SDS default, sni)
istioctl proxy-config cluster client.$NS --fqdn t91-egress.$NS.svc.homelab.local -o json | \
  jq '.[] | select(.name|contains("|partner|")) | {name, max:.circuitBreakers.thresholds[0].maxConnections,
      ka:.upstreamConnectionOptions.tcpKeepalive, sni:.transportSocket.typedConfig.sni}'
# hop2 -> GATEWAY cluster (expect max=222, transportSocket ABSENT = raw TCP)
istioctl proxy-config cluster deploy/t91-egress -n "$NS" --fqdn api.partner.example -o json | \
  jq '.[] | select(.name=="outbound|443||api.partner.example") | {name,
      max:.circuitBreakers.thresholds[0].maxConnections,
      transportSocket:(.transportSocket // "ABSENT (raw TCP)")}'
# SPIFFE enforcement on hop1 listener
istioctl proxy-config listener deploy/t91-egress -n "$NS" --port 8443 -o json | \
  grep -E 'requireClientCertificate'
# bonus: exportTo ["."] does NOT hide DR2 from same-ns sidecars
istioctl proxy-config cluster client.$NS --fqdn api.partner.example -o json | \
  jq '.[] | {name, max:.circuitBreakers.thresholds[0].maxConnections, ts:(.transportSocket // "ABSENT")}'

# ---------- 6. cleanup ----------
# kubectl delete ns "$NS"   # mock.istio-verify-ext is shared infra — leave it
