#!/bin/bash
# 실습 #12 ① — 기본 LB (roundrobin + healthcheck + stats UI)
set -e

CFG="$(dirname "$0")/configs/01_haproxy_basic.cfg"

# 1) 백엔드 2개 (Nginx 컨테이너)
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) HAProxy 설치 + 설정 배포
sudo apt install -y haproxy
sudo cp "$CFG" /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
sudo systemctl restart haproxy

# 3) 분산 검증
echo
echo "=== roundrobin 검증 (10회 요청) ==="
for i in {1..10}; do curl -s http://localhost/; done | sort | uniq -c

# 4) Failover 시연
echo
echo "=== be1 다운 시뮬레이션 ==="
docker stop be1
sleep 5
echo "→ be1 down 후 5초 후 요청:"
for i in {1..5}; do curl -s http://localhost/; done | sort | uniq -c

# 5) 정리 (be1 복구)
docker start be1
echo
echo "→ Stats UI: http://localhost:8404/  (anon 접근, 응용 ④ 에서 auth 추가)"
