#!/bin/bash

# OpenClaw 一键恢复脚本
# 用法: ./restore.sh
# 或指定备份目录: ./restore.sh /path/to/backup

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKUP_DIR="${1:-$SCRIPT_DIR}"

echo -e "${YELLOW}========================================${NC}"
echo -e "${YELLOW}   OpenClaw 一键恢复脚本${NC}"
echo -e "${YELLOW}========================================${NC}"
echo ""

# 检查是否为 backup 目录
if [[ ! -d "$BACKUP_DIR/openclaw" ]]; then
    echo -e "${RED}错误: 不是有效的备份目录${NC}"
    echo "请确保目录包含 openclaw/ workspace/ 等文件夹"
    exit 1
fi

echo -e "${GREEN}[1/4] 检查备份文件...${NC}"
if [[ -d "$BACKUP_DIR/openclaw" ]]; then
    echo "  ✅ OpenClaw 配置: 存在"
else
    echo "  ❌ OpenClaw 配置: 不存在"
fi

if [[ -d "$BACKUP_DIR/workspace" ]]; then
    echo "  ✅ 工作区文件: 存在"
else
    echo "  ❌ 工作区文件: 不存在"
fi

if [[ -d "$BACKUP_DIR/vector_memory" ]]; then
    echo "  ✅ 向量记忆: 存在"
else
    echo "  ⚠️ 向量记忆: 不存在 (可选)"
fi

echo ""
echo -e "${GREEN}[2/4] 恢复 OpenClaw 配置...${NC}"
if [[ -d "$HOME/.openclaw" ]]; then
    echo "  ⚠️ 检测到现有 OpenClaw 配置，是否覆盖? (y/n)"
    read -r confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        echo "已取消恢复"
        exit 0
    fi
fi

# 创建必要目录
mkdir -p "$HOME/.openclaw"

# 复制文件
cp -r "$BACKUP_DIR/openclaw/"* "$HOME/.openclaw/" 2>/dev/null || true
echo "  ✅ OpenClaw 配置已恢复"

echo ""
echo -e "${GREEN}[3/4] 恢复工作区...${NC}"
mkdir -p "$HOME/.openclaw/workspace"
cp -r "$BACKUP_DIR/workspace/"* "$HOME/.openclaw/workspace/" 2>/dev/null || true
echo "  ✅ 工作区已恢复"

echo ""
echo -e "${GREEN}[4/4] 恢复向量记忆 (可选)...${NC}"
if [[ -d "$BACKUP_DIR/vector_memory" ]]; then
    mkdir -p "$HOME/openclaw-memory-vector"
    cp -r "$BACKUP_DIR/vector_memory/"* "$HOME/openclaw-memory-vector/" 2>/dev/null || true
    echo "  ✅ 向量记忆已恢复"
else
    echo "  ⏭️ 跳过向量记忆恢复"
fi

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}   恢复完成! ✅${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo "下一步操作:"
echo "  1. 重启 OpenClaw 服务: openclaw gateway restart"
echo "  2. 检查配置: openclaw status"
echo ""
