#!/bin/bash
# ============================================
# LiteMall 轻商城 - 数据库备份脚本
# ============================================
# 备份到 /root/backups/litemall/
# 保留最近30天备份，超期自动清理
# ============================================

set -e

BACKUP_DIR="/root/backups/litemall"
DATA_DIR="/root/.openclaw/workspace/lobster-mall/server/data"
RETENTION_DAYS=30

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

# 当前时间戳
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/litemall-${TIMESTAMP}.db"
BACKUP_LOG="${BACKUP_DIR}/backup.log"

# 执行备份（使用SQLite的备份模式，确保一致性）
if command -v sqlite3 &> /dev/null; then
    sqlite3 "${DATA_DIR}/litemall.db" ".backup '${BACKUP_FILE}'"
else
    cp "${DATA_DIR}/litemall.db" "${BACKUP_FILE}"
fi

# 压缩
gzip -f "$BACKUP_FILE"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] 备份完成: ${BACKUP_FILE}.gz ($(du -h ${BACKUP_FILE}.gz | cut -f1))" >> "$BACKUP_LOG"

# 清理过期备份
find "$BACKUP_DIR" -name "litemall-*.gz" -mtime +${RETENTION_DAYS} -delete

# 保留最近5个备份不删除（额外保护）
BACKUP_COUNT=$(ls -1 "${BACKUP_DIR}"/litemall-*.gz 2>/dev/null | wc -l)
echo "[$(date '+%Y-%m-%d %H:%M:%S')] 当前备份数: ${BACKUP_COUNT}, 清理阈值: ${RETENTION_DAYS}天" >> "$BACKUP_LOG"
