#!/bin/bash

# 记账本定时备份脚本
# 备份目录: /opt/backup/data/YYYYMMDD/accountbook

# 配置
SOURCE_DIR="/opt/accountbook"
BACKUP_ROOT="/opt/backup/data"
DATE=$(date +%Y%m%d)
BACKUP_DIR="${BACKUP_ROOT}/${DATE}/accountbook"

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

# 备份数据库文件
if [ -f "${SOURCE_DIR}/accountbook.db" ]; then
    cp "${SOURCE_DIR}/accountbook.db" "${BACKUP_DIR}/accountbook.db"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 数据库已备份: ${BACKUP_DIR}/accountbook.db"
else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 警告: 数据库文件不存在"
fi

# 备份源代码 (可选 - 根据需求可注释掉)
if [ -d "${SOURCE_DIR}/public" ]; then
    cp -r "${SOURCE_DIR}/public" "${BACKUP_DIR}/"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] public 目录已备份"
fi

# 备份前端代码
if [ -d "${SOURCE_DIR}/frontend" ]; then
    cp -r "${SOURCE_DIR}/frontend" "${BACKUP_DIR}/"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] frontend 目录已备份"
fi

# 备份配置文件
if [ -f "${SOURCE_DIR}/package.json" ]; then
    cp "${SOURCE_DIR}/package.json" "${BACKUP_DIR}/"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] package.json 已备份"
fi

echo "[$(date '+%Y-%m-%d %H:%M:%S')] 备份完成: ${BACKUP_DIR}"

# 清理30天前的旧备份
find "${BACKUP_ROOT}" -type d -name "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]" -mtime +30 -exec rm -rf {} \; 2>/dev/null
echo "[$(date '+%Y-%m-%d %H:%M:%S')] 30天前的旧备份已清理"
