#!/bin/bash

# 自动备份脚本
# 每天定时运行，备份当前工作区

set -e

echo "🔄 开始自动备份 $(date '+%Y-%m-%d %H:%M:%S')..."

# 工作区路径
WORKSPACE_DIR="/root/.openclaw/workspace"
BACKUP_DIR="$WORKSPACE_DIR/backups"

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

# 生成备份文件名
BACKUP_FILE="$BACKUP_DIR/backup-$(date '+%Y%m%d_%H%M%S').tar.gz"

# 排除不需要备份的文件
exclude_patterns=(
  '*.pyc'
  '__pycache__'
  'backups'
  'node_modules'
  '.venv'
  '*.log'
  '*.tmp'
)

# 构建排除参数
EXCLUDE_ARGS=()
for pattern in "${exclude_patterns[@]}"; do
  EXCLUDE_ARGS+=(--exclude="$pattern")
done

echo "📦 打包工作区..."

# 创建备份
tar -czf "$BACKUP_FILE" \
  --exclude-vcs \
  --exclude="*.pyc" \
  --exclude="__pycache__" \
  --exclude="backups" \
  --exclude="node_modules" \
  --exclude=".venv" \
  --exclude="*.log" \
  --exclude="*.tmp" \
  -C "$WORKSPACE_DIR" .

BACKUP_SIZE=$(du -h "$BACKUP_FILE" | cut -f1)

echo "✅ 备份完成: $(basename "$BACKUP_FILE")"
echo "   📏 大小: $BACKUP_SIZE"
echo "   📍 位置: $BACKUP_FILE"

# 保留最近30个备份
echo "🧹 清理旧备份（保留最近30个）..."
cd "$BACKUP_DIR"
ls -t *.tar.gz | tail -n +31 | xargs -r rm -f

# 显示备份状态
echo ""
echo "📊 备份状态:"
ls -lh *.tar.gz | tail -5

echo ""
echo "🎉 自动备份完成！"