#!/bin/bash
# =============================================================================
# MOMO Pro System - 防火牆白名單配置
# 功能：設定 UAT ↔ GCP 互相白名單，限制外部訪問
# 版本：1.0.0
# 日期：2026-02-14
# =============================================================================

# ============================================
# 白名單 IP 定義
# ============================================

# UAT IP (UAT VM IP - actual server IP)
UAT_IP="114.32.151.246"

# GCP IP (GCP VM IP)
GCP_IP="35.194.233.141"

# 辦公室/家庭 IP (需要能訪問監控服務的 IP)
# 請根據實際情況更新
ALLOWED_EXTERNAL_IPS=(
    "114.32.151.246"    # WOOO 辦公室 IP (範例)
    "1.160.0.0/16"      # 中華電信 ADSL 範圍 (範例)
    "192.168.1.0/24"    # 新增家庭網路範圍
    "10.0.0.0/8"        # 新增內網範圍
    "172.16.0.0/12"     # 新增內網範圍
    "192.168.0.0/16"    # 新增家庭網路範圍
    "10.10.0.0/16"      # 新增內網範圍
    "172.20.0.0/14"     # 新增內網範圍
)

# GCP 專案資訊
GCP_PROJECT="astral-gateway-484913-d7"
GCP_VM="momo-pro-gcp"
GCP_ZONE="asia-east1-b"

# ============================================
# UAT 防火牆配置 (UFW)
# ============================================
configure_uat_firewall() {
    echo "=========================================="
    echo "配置 UAT 防火牆白名單"
    echo "=========================================="

    ssh wooo@${UAT_IP} "
        # 重置 UFW
        sudo ufw --force reset

        # 預設策略：拒絕入站，允許出站
        sudo ufw default deny incoming
        sudo ufw default allow outgoing

        # 允許 SSH（所有 IP，但有 Fail2Ban 保護）
        sudo ufw allow 22/tcp

        # 允許 HTTP/HTTPS（公開，但僅有 Nginx 監聽）
        sudo ufw allow 80/tcp
        sudo ufw allow 443/tcp

        # 允許 GCP 訪問內部服務（用於監控/同步）
        sudo ufw allow from ${GCP_IP} to any port 5678 comment 'GCP -> n8n'
        sudo ufw allow from ${GCP_IP} to any port 8929 comment 'GCP -> GitLab'
        sudo ufw allow from ${GCP_IP} to any port 9090 comment 'GCP -> Prometheus'

        # 允許內網訪問所有服務
        sudo ufw allow from 192.168.0.0/24 comment 'Local Network'

        # 允許指定外部 IP 訪問監控服務
        $(for ip in "${ALLOWED_EXTERNAL_IPS[@]}"; do
            echo "sudo ufw allow from ${ip} to any port 30030 comment 'External -> Grafana'"
            echo "sudo ufw allow from ${ip} to any port 8929 comment 'External -> GitLab'"
        done)

        # 啟用防火牆
        sudo ufw --force enable
        sudo ufw status verbose
    "
}

# ============================================
# GCP 防火牆配置 (gcloud)
# ============================================
configure_gcp_firewall() {
    echo "=========================================="
    echo "配置 GCP 防火牆白名單"
    echo "=========================================="

    # 刪除過於寬鬆的規則
    gcloud compute firewall-rules delete allow-momo-ports --project=${GCP_PROJECT} --quiet 2>/dev/null || true

    # 創建嚴格的規則

    # 1. 允許 HTTP/HTTPS（公開，Web 服務）
    gcloud compute firewall-rules create momo-allow-web \
        --project=${GCP_PROJECT} \
        --direction=INGRESS \
        --priority=1000 \
        --network=default \
        --action=ALLOW \
        --rules=tcp:80,tcp:443 \
        --source-ranges=0.0.0.0/0 \
        --description="Allow HTTP/HTTPS from anywhere" \
        2>/dev/null || echo "Rule momo-allow-web already exists"

    # 2. 允許 SSH 僅從 UAT IP
    gcloud compute firewall-rules create momo-allow-ssh-from-uat \
        --project=${GCP_PROJECT} \
        --direction=INGRESS \
        --priority=1000 \
        --network=default \
        --action=ALLOW \
        --rules=tcp:22 \
        --source-ranges=${UAT_IP}/32 \
        --description="Allow SSH only from UAT" \
        2>/dev/null || echo "Rule momo-allow-ssh-from-uat already exists"

    # 3. 允許 K8s API 僅從 UAT IP
    gcloud compute firewall-rules create momo-allow-k8s-from-uat \
        --project=${GCP_PROJECT} \
        --direction=INGRESS \
        --priority=1000 \
        --network=default \
        --action=ALLOW \
        --rules=tcp:6443 \
        --source-ranges=${UAT_IP}/32 \
        --description="Allow K8s API only from UAT" \
        2>/dev/null || echo "Rule momo-allow-k8s-from-uat already exists"

    # 4. 拒絕其他所有入站流量（GCP 預設已有此規則）

    echo ""
    echo "GCP 防火牆規則："
    gcloud compute firewall-rules list --project=${GCP_PROJECT} \
        --filter="name~momo" \
        --format="table(name,direction,sourceRanges,allowed)"
}

# ============================================
# Nginx 白名單配置
# ============================================
configure_nginx_whitelist() {
    echo "=========================================="
    echo "配置 Nginx 白名單（監控服務）"
    echo "=========================================="

    # 創建白名單配置文件
    ssh wooo@${UAT_IP} "
cat > /tmp/allowed_ips.conf << 'EOF'
# 允許的 IP 白名單
# UAT 內網
allow 192.168.0.0/24;

# GCP 正式環境
allow ${GCP_IP};

# 辦公室/家庭 IP
$(for ip in "${ALLOWED_EXTERNAL_IPS[@]}"; do
    echo "allow ${ip};"
done)

# 拒絕其他所有
deny all;
EOF

        sudo mv /tmp/allowed_ips.conf /etc/nginx/snippets/allowed_ips.conf
        echo '白名單配置已寫入 /etc/nginx/snippets/allowed_ips.conf'
    "

    echo ""
    echo "請在需要限制訪問的 Nginx location 中加入："
    echo "    include snippets/allowed_ips.conf;"
}

# ============================================
# 顯示當前狀態
# ============================================
show_status() {
    echo "=========================================="
    echo "當前防火牆狀態"
    echo "=========================================="

    echo ""
    echo "--- UAT UFW 狀態 ---"
    ssh wooo@${UAT_IP} "sudo ufw status numbered" 2>/dev/null || echo "UAT 連線失敗"

    echo ""
    echo "--- GCP 防火牆規則 ---"
    gcloud compute firewall-rules list --project=${GCP_PROJECT} \
        --format="table(name,direction,sourceRanges,allowed)" 2>/dev/null || echo "GCP 連線失敗"
}

# ============================================
# 主程式
# ============================================
main() {
    case "${1:-status}" in
        uat)
            configure_uat_firewall
            ;;
        gcp)
            configure_gcp_firewall
            ;;
        nginx)
            configure_nginx_whitelist
            ;;
        all)
            configure_uat_firewall
            configure_gcp_firewall
            configure_nginx_whitelist
            ;;
        status)
            show_status
            ;;
        *)
            echo "用法: $0 [uat|gcp|nginx|all|status]"
            echo ""
            echo "  uat    - 配置 UAT 防火牆 (UFW)"
            echo "  gcp    - 配置 GCP 防火牆 (gcloud)"
            echo "  nginx  - 配置 Nginx IP 白名單"
            echo "  all    - 配置所有防火牆"
            echo "  status - 顯示當前狀態（預設）"
            ;;
    esac
}

main "$@"
