#!/bin/bash

# 彩票项目定时备份脚本
# 备份时间: 每天 4:10

# 配置
SOURCE_DIR="/opt/lottery"
BACKUP_ROOT="/opt/backup/data"
PROJECT_NAME="lottery"

# 获取当前日期
DATE=$(date +%Y%m%d)
BACKUP_DIR="${BACKUP_ROOT}/${DATE}/${PROJECT_NAME}"

# 日志
LOG_FILE="/var/log/backup_lottery.log"

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

# 开始备份
log "========== 开始备份 =========="

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

# 备份项目源代码 (排除 node_modules 和 .git)
log "备份项目源代码..."
rsync -a --exclude='node_modules' --exclude='.git' --exclude='*.log' \
    "$SOURCE_DIR/" "$BACKUP_DIR/source/" 2>&1 | tee -a "$LOG_FILE"

if [ $? -eq 0 ]; then
    log "源代码备份完成"
else
    log "警告: 源代码备份出现问题"
fi

# 备份数据库
log "备份数据库..."
if [ -f "$SOURCE_DIR/server/db/lottery.db" ]; then
    mkdir -p "$BACKUP_DIR/db"
    cp "$SOURCE_DIR/server/db/lottery.db" "$BACKUP_DIR/db/"
    log "数据库备份完成"
else
    log "警告: 数据库文件不存在"
fi

# 备份上传文件
log "备份上传文件..."
if [ -d "$SOURCE_DIR/server/uploads" ]; then
    mkdir -p "$BACKUP_DIR/uploads"
    cp -r "$SOURCE_DIR/server/uploads/"* "$BACKUP_DIR/uploads/" 2>/dev/null
    log "上传文件备份完成"
else
    log "警告: 上传目录不存在"
fi

# 清理旧备份 (保留最近 30 天)
log "清理 30 天前的旧备份..."
find "$BACKUP_ROOT" -type d -mtime +30 -exec rm -rf {} \; 2>/dev/null

log "========== 备份完成 =========="
log ""

# 输出备份目录大小
du -sh "$BACKUP_DIR" | tee -a "$LOG_FILE"
