#!/bin/bash

echo "=== 重新启动 inkos 守护进程 ==="

# 停止所有 inkos 进程
echo "1. 停止 inkos 守护进程..."
/bin/inkos down >/dev/null 2>&1
pkill -f "inkos" >/dev/null 2>&1
sleep 2

# 清理临时文件
echo "2. 清理临时文件..."
rm -rf .novel-sync-temp/* 2>/dev/null || true

# 备份数据
echo "3. 备份当前状态..."
mkdir -p backup_$(date +%Y%m%d_%H%M%S)
cp -r books/末日重生-开局囤货十亿物资/story/state/* backup_*/ 2>/dev/null || true

# 验证数据完整性
echo "4. 验证数据完整性..."
echo "   章节数: $(ls -1 books/末日重生-开局囤货十亿物资/chapters/*.md | wc -l) 个文件"
echo "   索引文件: $(cat books/末日重生-开局囤货十亿物资/chapters/index.json | jq -r 'length') 条记录"

# 启动 inkos
echo "5. 启动 inkos 守护进程..."
nohup /bin/inkos up > inkos_startup_$(date +%Y%m%d_%H%M%S).log 2>&1 &

# 等待启动
sleep 5

echo "6. 检查进程状态..."
if ps aux | grep -q "inkos up" | grep -v grep; then
    echo "✅ inkos 守护进程已启动"
    PID=$(ps aux | grep "inkos up" | grep -v grep | awk '{print $2}')
    echo "   PID: $PID"
else
    echo "❌ inkos 守护进程启动失败"
    echo "   查看日志: cat inkos_startup_*.log"
fi

echo "=== 完成 ==="
