name: chaos / backup freshness

# M1 of chaos engineering: 每小时问一次 OSS 最新备份是多久以前的，
# >26h 就 fail（说明 epsilon cron 挂了，或凭证过期，或 OSS 挂了）。
# 设计见 brain/issues/005-chaos-engineering-backup-migration.md

on:
  schedule:
    - cron: "0 * * * *"   # 每小时 0 分
  workflow_dispatch:      # 手动触发测试用

jobs:
  check:
    name: 查 OSS 最新备份时间
    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: query OSS latest backup mtime
        id: check
        run: |
          set -euo pipefail

          # ssh epsilon 查 OSS daily/ 最新对象的 LastModifiedTime
          LAST_MOD=$(ssh root@${{ secrets.EPSILON_HOST }} \
            "aliyun --profile xiangqin oss ls oss://agentaily-backup-xiangqin-prod/daily/ \
             -e oss-cn-hangzhou.aliyuncs.com" \
            | grep -oE 'xiangqin-[0-9]{8}\.db\.gz' \
            | sort -u | tail -1)

          if [ -z "$LAST_MOD" ]; then
            echo "::error::OSS 里找不到任何 xiangqin-*.db.gz 备份文件"
            exit 1
          fi

          # 从文件名解析日期（xiangqin-YYYYMMDD.db.gz）
          DATE_STR=$(echo "$LAST_MOD" | grep -oE '[0-9]{8}')
          YEAR="${DATE_STR:0:4}"
          MONTH="${DATE_STR:4:2}"
          DAY="${DATE_STR:6:2}"
          LAST_EPOCH=$(date -d "${YEAR}-${MONTH}-${DAY} 02:00:00 +0800" +%s)
          NOW_EPOCH=$(date +%s)
          AGE_HOURS=$(( (NOW_EPOCH - LAST_EPOCH) / 3600 ))

          echo "最新备份文件: $LAST_MOD (${YEAR}-${MONTH}-${DAY} 02:00 +08:00)"
          echo "距今: ${AGE_HOURS}h"

          # 写 job summary（GHA UI 上能看到）
          cat <<EOF >> "$GITHUB_STEP_SUMMARY"
          ### Backup freshness check

          - 最新备份: \`$LAST_MOD\`
          - 距今: **${AGE_HOURS}h**
          - 阈值: 26h

          EOF

          if [ "$AGE_HOURS" -gt 26 ]; then
            echo "::error::Backup too old: ${AGE_HOURS}h > 26h threshold"
            echo "- 结论: ❌ **FAIL（备份腐烂）**" >> "$GITHUB_STEP_SUMMARY"
            exit 1
          fi

          echo "✓ OK: backup is ${AGE_HOURS}h old (< 26h)"
          echo "- 结论: ✅ OK" >> "$GITHUB_STEP_SUMMARY"
