#!/usr/bin/env bash
# T93: 번들 랩 킷(files/lab/)만으로 DR connectionPool 필드별 "발동"을 처음부터 끝까지
#      (cleanup -> setup -> s1..s7 -> cleanup) 라이브 재현할 수 있는지 검증한다.
#
# 검증하는 claim:
#   KIT. 번들 킷만으로 setup -> 7시나리오 -> cleanup 전체 생애주기 재현 가능(멱등)
#   S1. maxConnections:1        -> upstream_cx_overflow 발동 (+ gauge cx_open)
#   S2. +http1MaxPendingRequests:1 -> upstream_rq_pending_overflow 발동 + 503/UO
#   S3. maxRequestsPerConnection:1 -> upstream_cx_max_requests turnover(거부 아님)
#   S4. http.idleTimeout:2s     -> upstream_cx_idle_timeout
#   S5. tcp.maxConnectionDuration:5s -> upstream_cx_max_duration_reached
#   S6. connectTimeout:1s(blackhole) -> upstream_cx_connect_timeout + 503/UF
#   S7. config 반영 검증(발동 아님) + §5 미결점 실측(생략 필드 주입값 / maxConcurrentStreams 기본)
#
# 전제: kubectl 현재 컨텍스트가 대상 클러스터(이 실측은 homelab, k8s 1.30.6 / Istio 1.30.0),
#       istioctl + jq 사용 가능. 번들 킷은 이 파일 기준 ../../lab/ 에 있다.
set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LAB="$(cd "$SCRIPT_DIR/../../lab" && pwd)"
echo "LAB kit = $LAB"

# ── 0. 기존 잔재 철거 (멱등) ──
echo "[0/9] teardown any pre-existing conn-lab (bundle cleanup.sh; idempotency)"
bash "$LAB/cleanup.sh"

# ── 1. 번들 킷으로 fresh setup ──
# setup.sh: ns(injection) -> backend(fortio server, sidecar) -> client(fortio server +
#   proxyStatsMatcher 로 cx/rq/circuit_breakers 게이지 노출 + DNS capture) -> blackhole SE -> rollout.
echo "[1/9] bundle setup.sh (fresh build)"
bash "$LAB/setup.sh"
kubectl get ns conn-lab
kubectl -n conn-lab get pods -o wide

# ── 2~8. 시나리오 (각 run 내 before->after 델타로 판정; 카운터는 누적) ──
echo "[2/9] S1 maxConnections:1 -> upstream_cx_overflow"
bash "$LAB/run-scenario.sh" s1
echo "[3/9] S2 +http1MaxPendingRequests:1 -> upstream_rq_pending_overflow + 503/UO"
bash "$LAB/run-scenario.sh" s2
echo "[4/9] S3 maxRequestsPerConnection:1 -> upstream_cx_max_requests turnover"
bash "$LAB/run-scenario.sh" s3
echo "[5/9] S4 http.idleTimeout:2s -> upstream_cx_idle_timeout"
bash "$LAB/run-scenario.sh" s4
echo "[6/9] S5 tcp.maxConnectionDuration:5s -> upstream_cx_max_duration_reached"
bash "$LAB/run-scenario.sh" s5
echo "[7/9] S6 connectTimeout:1s(blackhole) -> upstream_cx_connect_timeout + 503/UF"
bash "$LAB/run-scenario.sh" s6
echo "[8/9] S7 config 반영 검증(§5 미결점 실측)"
bash "$LAB/run-scenario.sh" s7

# ── 9. cleanup + NotFound 재확인 ──
echo "[9/9] bundle cleanup.sh + confirm gone"
bash "$LAB/cleanup.sh"
kubectl get ns conn-lab   # -> Error from server (NotFound)

echo "done"
