name: chaos / backup integrity

# M2 of chaos engineering: 每日把最新备份拉到 epsilon 本地 gunzip +
# sqlite integrity_check + 核心表行数检查。
# 设计见 brain/issues/005-chaos-engineering-backup-migration.md

on:
  schedule:
    - cron: "0 5 * * *"   # UTC 05:00（= 北京 13:00，epsilon cron 02:00 后 11h）
  workflow_dispatch:

jobs:
  check:
    name: 拉最新备份到 epsilon 本地 + sqlite 完整性
    runs-on: ubuntu-latest
    steps:
      - uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: ${{ secrets.EPSILON_SSH_KEY }}

      - name: known_hosts
        run: |
          mkdir -p ~/.ssh
          ssh-keyscan ${{ secrets.EPSILON_HOST }} >> ~/.ssh/known_hosts

      - name: pull latest backup + integrity check
        run: |
          set -euo pipefail

          ssh root@${{ secrets.EPSILON_HOST }} 'bash -s' <<'REMOTE'
          set -euo pipefail

          BUCKET="agentaily-backup-xiangqin-prod"
          ENDPOINT="oss-cn-hangzhou.aliyuncs.com"
          TS=$(date +%Y%m%d%H%M%S)
          TMP_DIR="/tmp/chaos-backup-integrity-${TS}"
          mkdir -p "$TMP_DIR"
          trap 'rm -rf "$TMP_DIR"' EXIT

          # 1. 找最新备份文件名
          LATEST=$(aliyun --profile xiangqin oss ls "oss://${BUCKET}/daily/" -e "$ENDPOINT" \
              | grep -oE 'xiangqin-[0-9]{8}\.db\.gz' | sort -u | tail -1)
          if [ -z "$LATEST" ]; then
              echo "::error::No backup files found in OSS"
              exit 1
          fi
          echo "latest: $LATEST"

          # 2. 下载
          aliyun --profile xiangqin oss cp "oss://${BUCKET}/daily/${LATEST}" "${TMP_DIR}/${LATEST}" \
              -e "$ENDPOINT" --force
          ls -la "${TMP_DIR}/${LATEST}"

          # 3. gunzip
          gunzip "${TMP_DIR}/${LATEST}"
          DB_FILE="${TMP_DIR}/${LATEST%.gz}"

          # 4. sqlite integrity_check
          INTEGRITY=$(sqlite3 "$DB_FILE" 'PRAGMA integrity_check' | head -1)
          echo "integrity_check: $INTEGRITY"
          if [ "$INTEGRITY" != "ok" ]; then
              echo "::error::integrity_check failed: $INTEGRITY"
              exit 1
          fi

          # 5. 核心表行数
          USERS=$(sqlite3 "$DB_FILE" "SELECT COUNT(*) FROM users")
          TABLES=$(sqlite3 "$DB_FILE" "SELECT COUNT(*) FROM sqlite_master WHERE type='table'")
          echo "users count: $USERS"
          echo "tables count: $TABLES"

          # 6. 验证至少有核心表存在（schema 不腐）
          REQUIRED="users sessions auth_requests profiles"
          for t in $REQUIRED; do
              exists=$(sqlite3 "$DB_FILE" "SELECT name FROM sqlite_master WHERE type='table' AND name='$t'")
              if [ -z "$exists" ]; then
                  echo "::error::required table missing: $t"
                  exit 1
              fi
          done

          echo "✓ integrity OK / users=$USERS / tables=$TABLES"
          REMOTE

      - name: job summary
        if: always()
        run: |
          cat <<EOF >> "$GITHUB_STEP_SUMMARY"
          ### Backup integrity check

          每日拉最新备份到 epsilon 本地跑 \`sqlite3 PRAGMA integrity_check\` +
          核心表存在验证（\`users / sessions / auth_requests / profiles\`）。

          详情看 step output。
          EOF
