#!/bin/bash
# ════════════════════════════════════════════════════════════════
# 光湖 · Git Sync 服务一键部署脚本
# 在新服务器 ZY-CVM-MAIN 上执行
# ════════════════════════════════════════════════════════════════
#
# 功能：
# 1. 部署 Git Sync 服务到 /data/guanghulab/server/git-sync/
# 2. 用 PM2 启动并设置开机自启
# 3. 配置 Nginx 反向代理
# 4. 在 Gitea 配置 Webhook
#
# 前提：Forgejo 已运行，PM2 已安装，Nginx 已配置
# ════════════════════════════════════════════════════════════════

set -e

REPO_DIR="/data/guanghulab/repo"
SYNC_DIR="$REPO_DIR/server/git-sync"
TOKEN="e0fed57503db0d26046b7e30c51c80458da364b4"
GITEA_URL="http://127.0.0.1:3001"

echo "═══════════════════════════════════════"
echo "光湖 · Git Sync 部署"
echo "═══════════════════════════════════════"

# ─── 1. 同步代码到服务器 ───
echo ""
echo "▸ 步骤 1/5: 同步最新代码..."
cd "$REPO_DIR"
git fetch origin
git reset --hard origin/main
echo "✅ 代码已同步: $(git log --oneline -1)"

# ─── 2. 确保依赖已安装 ───
echo ""
echo "▸ 步骤 2/5: 安装依赖..."
if [ ! -d "$SYNC_DIR/node_modules" ]; then
  cd "$SYNC_DIR"
  npm install --production 2>/dev/null || true
  echo "✅ 依赖已安装"
else
  echo "✅ 依赖已存在，跳过"
fi

# ─── 3. 用 PM2 启动 Git Sync ───
echo ""
echo "▸ 步骤 3/5: 启动 Git Sync 服务..."

# 停止旧的（如果有）
pm2 delete guanghulab-git-sync 2>/dev/null || true

# 启动
cd "$SYNC_DIR"
ZY_REPO_TOKEN="$TOKEN" \
pm2 start server.js \
  --name guanghulab-git-sync \
  --env production

pm2 save
echo "✅ Git Sync 已启动 (端口 8082)"

# ─── 4. 配置 Nginx ───
echo ""
echo "▸ 步骤 4/5: 配置 Nginx 反向代理..."

NGINX_CONF="/etc/nginx/sites-enabled/guanghulab"

if grep -q "/sync/" "$NGINX_CONF" 2>/dev/null; then
  echo "✅ Nginx 已有 /sync/ 路由，跳过"
else
  # 在 /wake/ location 后面添加 /sync/ location
  sed -i '/location \/wake\//,/}/a\
\
    # ─── Git Sync 同步服务 (/sync/) ───\
    location /sync/ {\
        proxy_pass http://127.0.0.1:8082/;\
        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;\
    }' "$NGINX_CONF"

  nginx -t && systemctl reload nginx
  echo "✅ Nginx 已添加 /sync/ 路由"
fi

# ─── 5. 配置 Gitea Webhook ───
echo ""
echo "▸ 步骤 5/5: 配置 Gitea Webhook..."

# 生成 Webhook Secret
WEBHOOK_SECRET=$(openssl rand -hex 16)
echo "  Webhook Secret: $WEBHOOK_SECRET"

# 检查是否已存在 Webhook
EXISTING=$(curl -s -H "Authorization: token $TOKEN" \
  "$GITEA_URL/api/v1/repos/bingshuo/guanghulab/hooks" | \
  python3 -c "
import sys, json
hooks = json.load(sys.stdin)
for h in hooks:
    if h.get('config', {}).get('url', '').endswith('/sync/webhook'):
        print(h['id'])
        break
" 2>/dev/null || echo "")

if [ -n "$EXISTING" ]; then
  # 更新现有 Webhook
  curl -s -X PATCH -H "Authorization: token $TOKEN" \
    -H "Content-Type: application/json" \
    "$GITEA_URL/api/v1/repos/bingshuo/guanghulab/hooks/$EXISTING" \
    -d "{
      \"config\": {
        \"url\": \"http://127.0.0.1:8082/webhook\",
        \"content_type\": \"json\",
        \"secret\": \"$WEBHOOK_SECRET\"
      },
      \"events\": [\"push\"],
      \"active\": true
    }" > /dev/null
  echo "✅ Webhook 已更新 (ID: $EXISTING)"
else
  # 创建新 Webhook
  curl -s -X POST -H "Authorization: token $TOKEN" \
    -H "Content-Type: application/json" \
    "$GITEA_URL/api/v1/repos/bingshuo/guanghulab/hooks" \
    -d "{
      \"type\": \"gitea\",
      \"config\": {
        \"url\": \"http://127.0.0.1:8082/webhook\",
        \"content_type\": \"json\",
        \"secret\": \"$WEBHOOK_SECRET\"
      },
      \"events\": [\"push\"],
      \"active\": true
    }" > /dev/null
  echo "✅ Webhook 已创建"
fi

# 将 Secret 写入 Git Sync 环境变量
pm2 set guanghulab-git-sync:GIT_SYNC_SECRET "$WEBHOOK_SECRET" 2>/dev/null || true

# 重启 Git Sync 让环境变量生效
pm2 restart guanghulab-git-sync --update-env \
  --env ZY_REPO_TOKEN="$TOKEN" \
  --env GIT_SYNC_SECRET="$WEBHOOK_SECRET"

echo ""
echo "═══════════════════════════════════════"
echo "✅ Git Sync 部署完成！"
echo ""
echo "工作方式："
echo "  · 你在 Gitea 合并 PR → 自动触发 Webhook"
echo "  · Git Sync 收到通知 → 自动 git pull 到服务器"
echo "  · 代码立即可用，无需手动操作"
echo ""
echo "测试命令："
echo "  curl http://127.0.0.1:8082/health"
echo "  curl http://127.0.0.1:8082/status"
echo "═══════════════════════════════════════"
