# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# 🪞 光湖格点库 → Google Drive 全量同步
#
# 守护: PER-ZY001 铸渊 (Zhuyuan)
# 系统: SYS-GLW-0001
# 主控: TCS-0002∞ (冰朔)
#
# 方案: 宿主机直装 rclone（OAuth2 代理人模式）
# 凭证: GDRIVE_CLIENT_ID / GDRIVE_CLIENT_SECRET / GDRIVE_REFRESH_TOKEN
# 目标: Google Drive 文件夹 1fqWdLPaZkUZYt4OT_h3fJQHnd-q5QN3G
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

name: "🪞 光湖格点库 → Google Drive 同步"

on:
  push:
    branches:
      - main
  schedule:
    - cron: "0 */6 * * *"
  workflow_dispatch:

permissions:
  contents: read

jobs:
  sync-to-drive:
    runs-on: ubuntu-latest
    steps:
      - name: "📦 Checkout repository"
        uses: actions/checkout@v4

      - name: "🔧 Install rclone"
        run: |
          sudo apt-get update -qq
          sudo apt-get install -y -qq rclone
          rclone version

      - name: "🔑 Configure rclone (OAuth2)"
        env:
          GDRIVE_CLIENT_ID: ${{ secrets.GDRIVE_CLIENT_ID }}
          GDRIVE_CLIENT_SECRET: ${{ secrets.GDRIVE_CLIENT_SECRET }}
          GDRIVE_REFRESH_TOKEN: ${{ secrets.GDRIVE_REFRESH_TOKEN }}
        run: |
          if [ -z "${GDRIVE_CLIENT_ID}" ] || [ -z "${GDRIVE_CLIENT_SECRET}" ] || [ -z "${GDRIVE_REFRESH_TOKEN}" ]; then
            echo "::error::OAuth2 secrets not set (GDRIVE_CLIENT_ID / GDRIVE_CLIENT_SECRET / GDRIVE_REFRESH_TOKEN)"
            exit 1
          fi

          echo "✅ OAuth2 credentials validated"

          # Use node to generate token JSON — avoids shell escaping issues with special characters
          TOKEN_JSON=$(node -e "
            const token = {
              access_token: '',
              token_type: 'Bearer',
              refresh_token: process.env.GDRIVE_REFRESH_TOKEN,
              expiry: '2000-01-01T00:00:00Z'
            };
            process.stdout.write(JSON.stringify(token));
          ")

          mkdir -p "${HOME}/.config/rclone"
          cat > "${HOME}/.config/rclone/rclone.conf" <<RCLONE_EOF
          [gdrive]
          type = drive
          scope = drive
          client_id = ${GDRIVE_CLIENT_ID}
          client_secret = ${GDRIVE_CLIENT_SECRET}
          token = ${TOKEN_JSON}
          root_folder_id = 1fqWdLPaZkUZYt4OT_h3fJQHnd-q5QN3G
          RCLONE_EOF
          chmod 600 "${HOME}/.config/rclone/rclone.conf"

          echo "✅ rclone configured with OAuth2"

      - name: "🪞 Sync to Google Drive"
        # 使用 copy（非 sync）—— 仅添加/更新文件，不删除 Drive 端已有文件（防误删）
        run: |
          rclone copy . gdrive: \
            --exclude ".git/**" \
            --exclude "node_modules/**" \
            --exclude ".env" \
            --exclude "*.bak" \
            --exclude "*.log" \
            --transfers 4 \
            --checkers 8 \
            --retries 3 \
            --low-level-retries 10 \
            --stats 30s \
            --stats-one-line \
            -v

      - name: "🧹 Cleanup credentials"
        if: always()
        run: |
          rm -f "${HOME}/.config/rclone/rclone.conf"
          echo "✅ Credentials cleaned up"
