#!/bin/bash
# OpenClaw 每周自动备份脚本
# 运行时间: 每周日凌晨 2:00

BACKUP_DIR="/root/openclaw-backups"
DATE=$(date +%Y%m%d-%H%M%S)
BACKUP_FILE="$BACKUP_DIR/openclaw-weekly-$DATE.tar.gz"

# 创建备份目录
mkdir -p "$BACKUP_DIR"

# 执行备份 - 只备份代码和配置，排除数据文件
# 排除: CSV数据、PNG图表、HTML报告、__pycache__、.pyc、.log、.tar.gz等
tar -czf "$BACKUP_FILE" \
  -C /root/.openclaw \
  --exclude='workspace/**/__pycache__' \
  --exclude='workspace/**/*.pyc' \
  --exclude='workspace/**/*.csv' \
  --exclude='workspace/**/*.png' \
  --exclude='workspace/**/*.jpg' \
  --exclude='workspace/**/*.jpeg' \
  --exclude='workspace/**/*.html' \
  --exclude='workspace/**/*.log' \
  --exclude='workspace/**/*.tar.gz' \
  --exclude='workspace/**/backtest_result*' \
  --exclude='workspace/**/optimization_results*' \
  --exclude='workspace/**/backtest_results*' \
  --exclude='workspace/**/best_config*' \
  --exclude='workspace/**/last_*_days_report*' \
  --exclude='workspace/**/param_optimization*' \
  --exclude='workspace/**/quant_report*' \
  --exclude='openclaw-backup-*.tar.gz' \
  workspace/ \
  openclaw.json \
  openclaw.json.bak \
  openclaw.json.bak.1 \
  openclaw.json.bak.2 \
  openclaw.json.bak.3 \
  openclaw.json.bak.4 2>/dev/null

# 检查备份是否成功
if [ $? -eq 0 ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] ✓ OpenClaw 备份成功: $BACKUP_FILE"
    echo "  文件大小: $(du -h $BACKUP_FILE | cut -f1)"
    
    # 只保留最近4个备份（约1个月）
    ls -t $BACKUP_DIR/openclaw-weekly-*.tar.gz | tail -n +5 | xargs -r rm -f
    echo "  已清理旧备份，保留最近4个"
else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] ✗ OpenClaw 备份失败"
    exit 1
fi
