#!/bin/bash
# =============================================================================
# WOOO TECH - Monitor 入口頁面 + SSL 一鍵設置
# 在 UAT Server (192.168.0.110) 上執行
# =============================================================================

set -e

echo "=========================================="
echo "  WOOO TECH - Monitor 設置腳本"
echo "=========================================="

# 1. 更新入口頁面
echo ""
echo "[1/4] 更新 Monitor 入口頁面..."
sudo cp /home/wooo/momo_pro_system/k8s/nginx/monitor-index.html /var/www/monitor/index.html
echo "✅ 入口頁面已更新"

# 2. 申請 SSL 證書 (如果還沒有)
echo ""
echo "[2/4] 檢查/申請 SSL 證書..."
for domain in monitor.wooo.work gitlab.wooo.work cloud.wooo.work; do
    if [ ! -d "/etc/letsencrypt/live/$domain" ]; then
        echo "  申請 $domain 證書..."
        sudo certbot certonly --nginx -d $domain --non-interactive --agree-tos -m admin@wooo.work || true
    else
        echo "  $domain 證書已存在"
    fi
done
echo "✅ SSL 證書檢查完成"

# 3. 備份並更新 nginx 配置
echo ""
echo "[3/4] 更新 Nginx 配置..."
if [ -f /etc/nginx/sites-available/monitor ]; then
    sudo cp /etc/nginx/sites-available/monitor /etc/nginx/sites-available/monitor.bak.$(date +%Y%m%d_%H%M%S)
fi
sudo cp /home/wooo/momo_pro_system/k8s/nginx/monitor.conf /etc/nginx/sites-available/monitor

# 4. 測試並重載 nginx
echo ""
echo "[4/4] 測試並重載 Nginx..."
sudo nginx -t
sudo systemctl reload nginx
echo "✅ Nginx 已重載"

echo ""
echo "=========================================="
echo "  設置完成！"
echo "=========================================="
echo ""
echo "現在可以訪問："
echo "  - https://monitor.wooo.work/ (監控入口)"
echo "  - https://gitlab.wooo.work/"
echo "  - https://cloud.wooo.work/"
echo ""
