#!/bin/bash
# 실습 #12 ③ — Sticky Session (cookie 기반)
set -e

CFG="$(dirname "$0")/configs/03_haproxy_sticky.cfg"

# 1) 백엔드 준비
docker rm -f be1 be2 2>/dev/null || true
docker run -d --name be1 -p 8001:80 nginx
docker run -d --name be2 -p 8002:80 nginx
docker exec be1 sh -c "echo 'Backend-1' > /usr/share/nginx/html/index.html && echo OK > /usr/share/nginx/html/health"
docker exec be2 sh -c "echo 'Backend-2' > /usr/share/nginx/html/index.html && echo OK > /usr/share/nginx/html/health"

# 2) 설정 배포
sudo cp "$CFG" /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
sudo systemctl reload haproxy

# 3) 쿠키 sticky 검증 (같은 cookie jar 사용)
echo
echo "=== sticky session 검증 ==="
JAR=/tmp/lab12.jar
rm -f "$JAR"
echo "→ 첫 요청 (cookie 발급)"
curl -s -c "$JAR" http://localhost/
echo "발급된 SERVERID 쿠키:"
grep SERVERID "$JAR" | awk '{print "  ", $NF}'
echo
echo "→ 같은 cookie 로 5회 요청 — 모두 같은 백엔드여야 함"
for i in {1..5}; do curl -s -b "$JAR" http://localhost/; done | sort | uniq -c
echo
echo "→ cookie 없이 요청 — 분산 (roundrobin)"
for i in {1..6}; do curl -s http://localhost/; done | sort | uniq -c
rm -f "$JAR"
