#!/bin/bash
# =============================================================================
# MOMO Pro System - 監控服務白名單設定
# 功能：限制監控/報表服務只允許白名單 IP 訪問
# 執行方式：在 UAT 主機上以 root 或 sudo 執行
# =============================================================================

set -e

echo "=========================================="
echo "🔒 監控服務白名單設定"
echo "=========================================="

# Step 1: 創建白名單配置
echo ""
echo "Step 1: 創建白名單配置..."

cat > /etc/nginx/snippets/monitor_whitelist.conf << 'EOF'
# =============================================================================
# 監控服務白名單 (monitor.wooo.work)
# 只允許以下 IP 訪問 Superset, Metabase, Grafana, n8n 等服務
# 更新日期: 2026-02-14
# =============================================================================

# ----- 內部網路 -----
# UAT 內網
allow 192.168.0.0/24;

# ----- 伺服器間通訊 -----
# GCP 正式環境 (momo.wooo.work 需要訪問 BI 服務)
allow 35.194.233.141;

# Ollama AI 伺服器
allow 192.168.0.188;

# ----- 辦公室/家庭 IP (請依實際情況添加) -----
# 範例：allow 114.32.151.246;

# ----- 拒絕其他所有 -----
deny all;
EOF

echo "✅ 白名單配置已創建: /etc/nginx/snippets/monitor_whitelist.conf"

# Step 2: 備份現有 Nginx 配置
echo ""
echo "Step 2: 備份現有配置..."
cp /etc/nginx/sites-enabled/monitor /etc/nginx/sites-enabled/monitor.backup.$(date +%Y%m%d_%H%M%S)
echo "✅ 備份完成"

# Step 3: 修改 monitor 配置，加入白名單
echo ""
echo "Step 3: 修改 monitor.wooo.work 配置..."

# 檢查是否已包含白名單
if grep -q "monitor_whitelist.conf" /etc/nginx/sites-enabled/monitor; then
    echo "⚠️ 白名單已配置，跳過修改"
else
    # 在 server 塊開頭加入白名單
    sed -i '/server_name monitor.wooo.work;/a\    # 白名單限制\n    include snippets/monitor_whitelist.conf;' /etc/nginx/sites-enabled/monitor
    echo "✅ 已加入白名單引用"
fi

# Step 4: 測試 Nginx 配置
echo ""
echo "Step 4: 測試 Nginx 配置..."
nginx -t

# Step 5: 重載 Nginx
echo ""
echo "Step 5: 重載 Nginx..."
systemctl reload nginx
echo "✅ Nginx 已重載"

# Step 6: 驗證
echo ""
echo "=========================================="
echo "🎉 設定完成！"
echo "=========================================="
echo ""
echo "白名單 IP："
grep "^allow" /etc/nginx/snippets/monitor_whitelist.conf
echo ""
echo "測試訪問："
echo "  ✅ 從內網: curl https://monitor.wooo.work/superset/"
echo "  ✅ 從 GCP: curl https://monitor.wooo.work/superset/"
echo "  ❌ 從外網: 應返回 403 Forbidden"
echo ""
echo "如需添加新的白名單 IP，請編輯："
echo "  /etc/nginx/snippets/monitor_whitelist.conf"
echo "然後執行: sudo systemctl reload nginx"
