#!/usr/bin/env bash
# ════════════════════════════════════════════════════════════════
# 光湖 · Nginx 修复脚本
# 修复之前 deploy-mcp.sh 和 fix-nginx.sh 遗留的问题
# ════════════════════════════════════════════════════════════════
#
# 问题:
#   1. deploy-mcp.sh 用 sed 把 /mcp 块插到 /wake/ 块内部
#   2. fix-nginx.sh 修复后又创建了 .bak 文件
#   3. nginx 加载 sites-enabled/ 下所有文件，包括 .bak
#
# 解决:
#   直接用仓库中的正确配置覆盖，删除所有 .bak 文件
#
# 用法: bash fix-nginx-v2.sh
#
# 签发: 铸渊 · ICE-GL-ZY001
# ════════════════════════════════════════════════════════════════

set -e

REPO_DIR="/data/guanghulab/repo"
NGINX_CONF_SRC="$REPO_DIR/server/nginx/guanghulab-cvm.conf"
NGINX_CONF_DST="/etc/nginx/sites-enabled/guanghulab"

echo "═══════════════════════════════════════"
echo "  光湖 · Nginx 修复 v2"
echo "  $(date '+%Y-%m-%d %H:%M:%S')"
echo "═══════════════════════════════════════"

# ─── 1. 删除所有 .bak 文件 ─────────────────────────────────
echo ""
echo "── 1. 清理 .bak 文件 ──"

BAK_COUNT=0
for f in /etc/nginx/sites-enabled/guanghulab.bak* /etc/nginx/sites-enabled/*.bak*; do
    if [ -f "$f" ]; then
        echo "   删除: $f"
        rm -f "$f"
        BAK_COUNT=$((BAK_COUNT+1))
    fi
done

if [ "$BAK_COUNT" -gt 0 ]; then
    echo "✅ 已删除 $BAK_COUNT 个 .bak 文件"
else
    echo "✅ 没有 .bak 文件需要清理"
fi

# ─── 2. 用仓库中的正确配置覆盖 ──────────────────────────────
echo ""
echo "── 2. 替换 Nginx 配置 ──"

if [ ! -f "$NGINX_CONF_SRC" ]; then
    echo "❌ 仓库中找不到参考配置: $NGINX_CONF_SRC"
    echo "   请先 git pull 更新代码"
    exit 1
fi

# 备份当前配置（放到 /data/ 而不是 sites-enabled/，避免 nginx 加载）
mkdir -p /data/guanghulab/.runtime/nginx-backup
cp "$NGINX_CONF_DST" "/data/guanghulab/.runtime/nginx-backup/guanghulab.$(date +%Y%m%d%H%M%S)" 2>/dev/null || true

# 直接覆盖
cp "$NGINX_CONF_SRC" "$NGINX_CONF_DST"
echo "✅ 配置已替换: $NGINX_CONF_DST"

# ─── 3. 确保 sites-enabled/ 中没有其他冲突配置 ─────────────
echo ""
echo "── 3. 检查 sites-enabled/ ──"

OTHER_CONF=""
for f in /etc/nginx/sites-enabled/*; do
    BASENAME=$(basename "$f")
    if [ "$BASENAME" != "guanghulab" ] && [ "$BASENAME" != "default" ]; then
        OTHER_CONF="$OTHER_CONF $f"
    fi
done

if [ -n "$OTHER_CONF" ]; then
    echo "⚠️  发现其他配置文件:$OTHER_CONF"
    echo "   请确认它们不会冲突"
else
    echo "✅ sites-enabled/ 整洁"
fi

# ─── 4. 测试 Nginx ──────────────────────────────────────────
echo ""
echo "── 4. 测试 Nginx 配置 ──"

if nginx -t 2>&1; then
    echo "✅ Nginx 配置测试通过"

    # 重载
    nginx -s reload
    echo "✅ Nginx 已重载"
else
    echo "❌ Nginx 配置测试失败"
    echo "   请检查 $NGINX_CONF_DST"
    exit 1
fi

# ─── 5. 验证服务 ────────────────────────────────────────────
echo ""
echo "── 5. 验证服务 ──"
sleep 1

# Nginx 级健康探针
if curl -sf http://127.0.0.1/health > /dev/null 2>&1; then
    echo "✅ Nginx 健康探针正常"
else
    if curl -sf https://127.0.0.1/health -k > /dev/null 2>&1; then
        echo "✅ Nginx 健康探针正常 (HTTPS)"
    else
        echo "⚠️  Nginx 健康探针未响应"
    fi
fi

# Forgejo
if curl -sf http://127.0.0.1:3001/ > /dev/null 2>&1; then
    echo "✅ Forgejo 运行中"
else
    echo "⚠️  Forgejo 未响应"
fi

# MCP Server
if curl -sf http://127.0.0.1:8083/health > /dev/null 2>&1; then
    echo "✅ MCP Server 运行中"
else
    echo "⚠️  MCP Server 未响应"
fi

# Wake Gate
if curl -sf http://127.0.0.1:8081/api/health > /dev/null 2>&1; then
    echo "✅ Wake Gate 运行中"
else
    echo "⚠️  Wake Gate 未响应"
fi

# Git Sync
if curl -sf http://127.0.0.1:8082/health > /dev/null 2>&1; then
    echo "✅ Git Sync 运行中"
else
    echo "⚠️  Git Sync 未响应"
fi

echo ""
echo "═══════════════════════════════════════"
echo "  Nginx 修复完成"
echo "  ICE-GL-ZY001 · TCS-0002∞"
echo "═══════════════════════════════════════"
