#!/bin/bash
# 실습 #13 ③ — notify 스크립트: state 변경 시 외부 알림 + 서비스 제어
set -e

CFG="$(dirname "$0")/configs/03_keepalived_notify.conf"

sudo apt install -y keepalived
# 1) notify 스크립트 3종 생성
sudo tee /etc/keepalived/notify_master.sh >/dev/null <<'EOF'
#!/bin/bash
logger -t keepalived "→ MASTER 전환: $(hostname)"
# 운영 활용 예: 슬랙 알림, HAProxy 시작 등
# curl -X POST -d "Master: $(hostname)" https://hooks.slack.com/...
# systemctl start haproxy
EOF

sudo tee /etc/keepalived/notify_backup.sh >/dev/null <<'EOF'
#!/bin/bash
logger -t keepalived "→ BACKUP 전환: $(hostname)"
# systemctl stop haproxy
EOF

sudo tee /etc/keepalived/notify_fault.sh >/dev/null <<'EOF'
#!/bin/bash
logger -t keepalived "‼️ FAULT 발생: $(hostname)"
EOF

sudo chmod +x /etc/keepalived/notify_*.sh

# 2) 설정 배포
sudo cp "$CFG" /etc/keepalived/keepalived.conf
sudo systemctl restart keepalived

echo
echo "=== notify 검증 (로그 모니터) ==="
echo "→ 별도 터미널에서: sudo journalctl -t keepalived -f"
echo "→ MASTER stop/start 반복하면 notify_*.sh 로그가 syslog 에 남음"
echo
echo "테스트:"
echo "  sudo systemctl stop keepalived   # → FAULT/BACKUP 알림"
echo "  sudo systemctl start keepalived  # → MASTER 알림"
