#!/bin/bash
# Cat-Fly 自动备份脚本
# 每天凌晨4点执行，备份到 Git 仓库

BACKUP_DIR="/tmp/cat-fly-backup-$(date +%Y%m%d)"
SOURCE_DIR="/root/.openclaw/workspace/cat-fly"
REPO_URL="http://openclaw:asdasd9981@code.erwin.wang/openclaw/openclaw-backup.git"
LOG_FILE="/var/log/catfly-backup.log"

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "开始备份..."

# 创建临时目录
rm -rf "$BACKUP_DIR"
mkdir -p "$BACKUP_DIR"

# 复制核心文件
cp "$SOURCE_DIR/auto_report.py" "$BACKUP_DIR/"
cp "$SOURCE_DIR/cyb50_30min_dual_direction.py" "$BACKUP_DIR/"
cp "$SOURCE_DIR/config.json" "$BACKUP_DIR/"
cp "$SOURCE_DIR/cron_jobs.json" "$BACKUP_DIR/"
cp "$SOURCE_DIR/README.md" "$BACKUP_DIR/"

# 添加备份信息
echo "Backup Date: $(date '+%Y-%m-%d %H:%M:%S')" > "$BACKUP_DIR/BACKUP_INFO.txt"
echo "Source: $SOURCE_DIR" >> "$BACKUP_DIR/BACKUP_INFO.txt"

# 克隆仓库并更新
cd /tmp
rm -rf openclaw-backup-temp
if ! git clone "$REPO_URL" openclaw-backup-temp 2>/dev/null; then
    log "错误: 无法克隆仓库"
    exit 1
fi

# 复制新文件到仓库
cd openclaw-backup-temp
rm -rf cat-fly/*
cp -r "$BACKUP_DIR"/* cat-fly/ 2>/dev/null || cp "$BACKUP_DIR"/* cat-fly/ 2>/dev/null

# Git 配置
git config user.email "backup@openclaw.local"
git config user.name "Auto Backup"

# 提交并推送
git add -A
if git diff --cached --quiet; then
    log "没有变更，跳过提交"
else
    git commit -m "Auto backup $(date '+%Y-%m-%d %H:%M:%S')"
    if git push origin master; then
        log "备份成功推送到仓库"
    else
        log "错误: 推送失败"
        exit 1
    fi
fi

# 清理
rm -rf "$BACKUP_DIR"
rm -rf /tmp/openclaw-backup-temp

log "备份完成"
