name: PR合并自动部署

on:
  pull_request:
    branches:
      - main
    types:
      - closed

jobs:
  deploy:
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest

    steps:
      - name: 配置SSH环境
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -H ${{ secrets.DEPLOY_HOST }} >> ~/.ssh/known_hosts

      - name: 远程执行部署
        run: |
          ssh -T -i ~/.ssh/deploy_key \
            ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} <<'EOF'

          set -e

          # ==============================
          # 项目目录
          # ==============================
          PROJECT="/www/wwwroot/Hulumath-Web-Demo"

          echo "========================================"
          echo "🚀 开始部署"
          echo "项目目录: $PROJECT"
          echo "========================================"

          cd "$PROJECT"

          echo "当前目录:"
          pwd

          # 防止 Git 因目录所有者不同而报 dubious ownership
          git config --global --add safe.directory "$PROJECT" || true

          # ==============================
          # 检查 Git 仓库
          # ==============================
          if [ ! -d ".git" ]; then
            echo "❌ 当前目录不是 Git 仓库"
            exit 1
          fi

          echo "✅ Git 仓库检查通过"

          # ==============================
          # 拉取远程 main
          # ==============================
          echo "📥 获取远程 main 分支..."
          git fetch origin main

          # ==============================
          # 判断本次提交是否修改数据库
          # ==============================
          DB_CHANGED=0

          if git diff --name-only HEAD origin/main | grep -qx "data/miniapp_v3.db"; then
            DB_CHANGED=1
            echo "⚠️ 本次代码提交包含数据库变更"
          else
            echo "✅ 本次代码提交未修改数据库"
          fi

          # ==============================
          # 备份当前运行时数据库
          # ==============================
          DB_BACKUP="/tmp/miniapp_v3.db.deploy_backup"

          rm -f "$DB_BACKUP"

          if [ -f "data/miniapp_v3.db" ]; then
            cp "data/miniapp_v3.db" "$DB_BACKUP"
            echo "✅ 已备份当前运行时数据库"
          else
            echo "ℹ️ 当前不存在运行时数据库"
          fi

          # ==============================
          # 更新代码
          # ==============================
          echo "🔄 更新代码到 origin/main..."

          git reset --hard origin/main

          echo "✅ 代码更新完成"

          # ==============================
          # 恢复运行时数据库
          #
          # 如果本次 PR 没修改数据库：
          #   保留服务器当前运行时数据库
          #
          # 如果本次 PR 修改了数据库：
          #   使用仓库中新版本数据库
          # ==============================
          if [ "$DB_CHANGED" -eq 0 ]; then
            if [ -f "$DB_BACKUP" ]; then
              cp "$DB_BACKUP" "data/miniapp_v3.db"
              echo "✅ 已恢复运行时数据库"
            fi
          else
            echo "ℹ️ 仓库包含数据库更新，不恢复旧数据库"
          fi

          rm -f "$DB_BACKUP"

          # ==============================
          # 安装 Python 依赖
          # ==============================
          echo "📦 安装 Python 依赖..."

          /www/server/pyporject_evn/versions/3.12.13/bin/pip \
            install -r requirements.txt

          echo "✅ Python 依赖安装完成"

          # ==============================
          # 修正权限
          # ==============================
          chown -R www:www "$PROJECT"

          # ==============================
          # Gunicorn 优雅重载
          # ==============================
          echo "🔄 准备重载 Gunicorn..."

          if [ -f "$PROJECT/gunicorn.pid" ]; then

            MASTER_PID=$(cat "$PROJECT/gunicorn.pid")

            echo "Gunicorn PID 文件中的进程: $MASTER_PID"

            if kill -0 "$MASTER_PID" 2>/dev/null; then

              kill -HUP "$MASTER_PID"

              echo "✅ Gunicorn 已发送 HUP，优雅重载完成"

            else

              echo "⚠️ gunicorn.pid 中的进程不存在"

            fi

          else

            # PID 文件不存在时备用查找
            MASTER_PID=$(pgrep -f "gunicorn.*gunicorn_conf.py" | head -n 1 || true)

            if [ -n "$MASTER_PID" ]; then

              echo "检测到 Gunicorn PID: $MASTER_PID"

              kill -HUP "$MASTER_PID"

              echo "✅ Gunicorn 已发送 HUP，优雅重载完成"

            else

              echo "⚠️ 未找到 Gunicorn 进程，跳过重载"

            fi

          fi

          echo "========================================"
          echo "✅ 部署完成"
          echo "========================================"

          EOF