name: Deploy to Server

on:
  push:
    branches:
      - main
      - master

jobs:
  deploy:
    runs-on: ubuntu
    steps:
      # 使用 Gitea 官方镜像加速 Checkout，避免连接 GitHub 超时
      - name: Checkout
        uses: https://gitea.com/actions/checkout@v3

      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y sshpass

      - name: Deploy to server
        env:
          HOST: "6.6.6.66"
          USER: "quant-speed"
          PASS: "123quant-speed"
          # 目标目录
          TARGET_DIR: "/home/quant-speed/data/dev/ESP32_GDEY042T81_server"
        run: |
          # 远程执行部署命令
          sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no $USER@$HOST "bash -s" <<EOF
            # 确保目标目录存在
            mkdir -p $TARGET_DIR
            cd $TARGET_DIR
            
            # 记录当前 HEAD，用于后续 diff
            OLD_HEAD=\$(git rev-parse HEAD 2>/dev/null || echo "")

            # 拉取最新代码
            echo "正在拉取最新代码..."
            git pull || { echo "Git pull failed"; exit 1; }

            NEW_HEAD=\$(git rev-parse HEAD)

            # 检查是否有代码更新
            if [ "\$OLD_HEAD" == "\$NEW_HEAD" ]; then
                echo "代码没有变化，无需重启"
                exit 0
            fi

            # 检查是否需要重新构建镜像 (Dockerfile 或 requirements.txt 变动)
            # 使用 git diff 检查此次 pull 更新的文件列表
            if git diff --name-only \$OLD_HEAD \$NEW_HEAD | grep -E 'Dockerfile|requirements.txt'; then
                echo "检测到构建文件变动，开始重新构建镜像..."
                echo "$PASS" | sudo -S docker compose down --rmi local
                # 确保清理干净
                echo "$PASS" | sudo -S docker rmi epaper_server:latest || true
                echo "$PASS" | sudo -S docker compose up -d --build
            else
                echo "仅代码变动，无需重新构建镜像，重启容器..."
                echo "$PASS" | sudo -S docker compose down
                echo "$PASS" | sudo -S docker compose up -d
            fi
          EOF
