#!/bin/bash
# 一次性設置維護模式和修復 Nginx timeout

echo "=========================================="
echo "設置維護模式和修復 Nginx timeout"
echo "=========================================="

# 創建 disable_maintenance.sh
cat > ~/disable_maintenance.sh << 'EOF'
#!/bin/bash
# 禁用維護模式腳本

echo "=========================================="
echo "禁用維護模式"
echo "=========================================="

# 恢復正常 Nginx 配置
echo "1. 恢復正常 Nginx 配置..."
sudo ln -sf /etc/nginx/sites-available/momo /etc/nginx/sites-enabled/momo

# 測試並重載 Nginx
echo "2. 重載 Nginx..."
sudo nginx -t && sudo systemctl reload nginx

echo ""
echo "=========================================="
echo "✅ 維護模式已禁用"
echo "=========================================="
echo "網址：https://mo.wooo.work"
echo "網站已恢復正常服務"
echo "=========================================="
EOF

chmod +x ~/disable_maintenance.sh
echo "✅ disable_maintenance.sh 已創建"

# 修復 Nginx timeout（增加到 300 秒）
echo ""
echo "修復 Nginx timeout 設置..."
sudo cp /etc/nginx/sites-available/momo /etc/nginx/sites-available/momo.timeout-backup

# 在 location / { 區塊內添加 timeout 設置
sudo sed -i '/location \/ {/a\        proxy_read_timeout 300s;\n        proxy_connect_timeout 300s;\n        proxy_send_timeout 300s;' /etc/nginx/sites-available/momo

# 測試並重載 Nginx
echo "測試 Nginx 配置..."
sudo nginx -t

if [ $? -eq 0 ]; then
    echo "重載 Nginx..."
    sudo systemctl reload nginx
    echo "✅ Nginx timeout 已修復（增加到 300 秒）"
else
    echo "❌ Nginx 配置測試失敗，恢復備份..."
    sudo cp /etc/nginx/sites-available/momo.timeout-backup /etc/nginx/sites-available/momo
fi

echo ""
echo "=========================================="
echo "✅ 設置完成"
echo "=========================================="
echo "維護模式腳本："
echo "  啟用：~/enable_maintenance.sh"
echo "  禁用：~/disable_maintenance.sh"
echo ""
echo "Nginx timeout 已設置為 300 秒"
echo "=========================================="
