#!/bin/bash
# ============================================
# LiteMall 轻商城 - 数据库恢复脚本
# ============================================
# 用法: bash restore.sh <备份文件路径>
# 示例: bash restore.sh /root/backups/litemall/litemall-20260613-180000.db.gz
# ============================================

set -e

if [ -z "$1" ]; then
    echo "❌ 用法: bash restore.sh <备份文件路径>"
    echo "📂 可用备份:"
    ls -lh /root/backups/litemall/*.gz 2>/dev/null || echo "    无备份文件"
    exit 1
fi

BACKUP_FILE="$1"
DATA_DIR="/root/.openclaw/workspace/lobster-mall/server/data"
TARGET="${DATA_DIR}/litemall.db"

if [ ! -f "$BACKUP_FILE" ]; then
    echo "❌ 备份文件不存在: $BACKUP_FILE"
    exit 1
fi

echo "⚠️  即将恢复数据库，当前数据将被覆盖！"

# 如果是压缩文件，先解压
if [[ "$BACKUP_FILE" == *.gz ]]; then
    gunzip -kf "$BACKUP_FILE" "${BACKUP_FILE%.gz}" 2>/dev/null || true
    RESTORE_FILE="${BACKUP_FILE%.gz}"
else
    RESTORE_FILE="$BACKUP_FILE"
fi

# 停止服务，防止写入冲突
pm2 stop litemall 2>/dev/null || echo "PM2未运行"

# 备份当前数据库（以防万一）
cp "$TARGET" "${TARGET}.pre-restore.$(date +%Y%m%d%H%M%S)" 2>/dev/null || true

# 恢复
cp "$RESTORE_FILE" "$TARGET"
echo "✅ 数据库已恢复: $RESTORE_FILE"

# 重启服务
pm2 restart litemall 2>/dev/null || echo "请手动启动服务"

echo "✅ 恢复完成，请验证数据完整性"
