#!/bin/bash
# setup_nginx.sh - 設定 Nginx 反向代理

set -e

echo "=========================================="
echo "設定 Nginx 反向代理"
echo "=========================================="

# 詢問域名或 IP
read -p "請輸入您的域名或 IP 地址 (例如: example.com 或 34.80.1.1): " DOMAIN

echo "📝 建立 Nginx 設定檔..."
sudo tee /etc/nginx/sites-available/momo > /dev/null <<EOF
server {
    listen 80;
    server_name $DOMAIN;

    # 上傳大小限制
    client_max_body_size 50M;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;

        # WebSocket 支援（如果需要）
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";

        # 超時設定
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # 靜態檔案快取
    location /static/ {
        alias /home/$USER/momo_pro_system/static/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
EOF

# 建立軟連結
echo "🔗 啟用站點..."
sudo ln -sf /etc/nginx/sites-available/momo /etc/nginx/sites-enabled/

# 移除預設站點
sudo rm -f /etc/nginx/sites-enabled/default

# 測試設定
echo "🧪 測試 Nginx 設定..."
sudo nginx -t

# 重啟 Nginx
echo "🔄 重啟 Nginx..."
sudo systemctl restart nginx
sudo systemctl enable nginx

echo ""
echo "✅ Nginx 設定完成！"
echo ""
echo "您的應用現在可以通過以下網址訪問："
echo "  http://$DOMAIN"
echo ""
echo "如需設定 HTTPS (SSL)，請執行："
echo "  sudo apt install certbot python3-certbot-nginx"
echo "  sudo certbot --nginx -d $DOMAIN"
