#!/bin/bash
# 실습 #12 ⑤ — 가중치 + backup 서버 (강화된 헬스체크)
set -e

CFG="$(dirname "$0")/configs/05_haproxy_weight_backup.cfg"

# 1) 백엔드 3개 (be3 = backup)
docker rm -f be1 be2 be3 2>/dev/null || true
docker run -d --name be1 -p 8001:80 nginx
docker run -d --name be2 -p 8002:80 nginx
docker run -d --name be3 -p 8003: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"
docker exec be3 sh -c "echo 'Backend-3 (backup)' > /usr/share/nginx/html/index.html && echo OK > /usr/share/nginx/html/health"

# 2) 설정 배포 (HTTP/1.1 + Host 헤더 명시 헬스체크)
sudo cp "$CFG" /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
sudo systemctl restart haproxy

sleep 3
# 3) weight 3:1 분배 검증 (be1 가 약 3배)
echo
echo "=== weight 3:1 분배 검증 (40회) ==="
for i in $(seq 1 40); do curl -s http://localhost/; done | sort | uniq -c
echo
echo "→ Backend-1 이 Backend-2 의 약 3배 출현해야 정상"

# 4) be1, be2 모두 죽이면 be3 (backup) 등판
echo
echo "=== be1·be2 동시 다운 → be3 (backup) 활성화 ==="
docker stop be1 be2
sleep 8
for i in {1..5}; do curl -s http://localhost/; done | sort | uniq -c

docker start be1 be2
