#!/bin/bash
# Trae IDE 重置脚本 - 清理缓存和重启服务

echo "🔄 Trae IDE 重置工具"
echo ""

# 停止所有 Trae 进程
echo "🛑 停止 Trae 进程..."
pkill -f trae || true
pkill -f "stable-8fe6088bdb0697eec2662377a7abd7f9791493c6" || true
sleep 3

# 清理缓存
echo "🧹 清理缓存和临时文件..."
rm -rf /home/ben/.trae-server/data/User/workspaceStorage/ || true
rm -rf /home/ben/.trae-server/data/logs/ || true
rm -rf /home/ben/.trae-server/extensions/ms-vscode.* || true

# 清理损坏的扩展
echo "🔧 清理损坏的扩展..."
find /home/ben/.trae-server/extensions/ -name "*claude-dev*" -type d -exec rm -rf {} + 2>/dev/null || true

# 重新生成 token
echo "🔑 生成新的连接 token..."
NEW_TOKEN=$(uuidgen)
echo "$NEW_TOKEN" > /home/ben/.trae-server/.stable-8fe6088bdb0697eec2662377a7abd7f9791493c6.token
chmod 600 /home/ben/.trae-server/.stable-8fe6088bdb0697eec2662377a7abd7f9791493c6.token

# 重启服务器
echo "🚀 重启 Trae 服务器..."
cd /home/ben/.trae-server/bin/stable-8fe6088bdb0697eec2662377a7abd7f9791493c6

nohup ./node ./index_trae.js \
    --start-server \
    --host=127.0.0.1 \
    --port=0 \
    --connection-token-file /home/ben/.trae-server/.stable-8fe6088bdb0697eec2662377a7abd7f9791493c6.token \
    --default-folder /home/ben/github/liurenchaxin \
    --server-data-dir /home/ben/.trae-server \
    --telemetry-level off \
    --enable-remote-auto-shutdown \
    --accept-server-license-terms \
    > /tmp/trae-reset.log 2>&1 &

# 等待启动
echo "⏳ 等待服务器启动..."
sleep 5

# 查找端口
SERVER_PID=$(pgrep -f "out/server-main.js.*--port")
if [ -n "$SERVER_PID" ]; then
    PORT=$(ss -tlnp | grep "node.*pid=$SERVER_PID" | grep -o ':4[0-9]*' | head -1 | cut -d':' -f2)
    
    if [ -n "$PORT" ]; then
        echo "✅ Trae 服务器重启成功！"
        echo ""
        echo "📝 新的连接信息:"
        echo "   地址: 127.0.0.1:$PORT"
        echo "   Token: $NEW_TOKEN"
        echo "   浏览器: http://127.0.0.1:$PORT/?folder=/home/ben/github/liurenchaxin"
        echo ""
        
        # 测试连接
        if curl -s -I "http://127.0.0.1:$PORT" | grep -q "405\|200"; then
            echo "✅ 服务器连接测试通过"
        else
            echo "⚠️  服务器连接测试失败"
        fi
    else
        echo "❌ 无法确定服务器端口"
        tail -10 /tmp/trae-reset.log
    fi
else
    echo "❌ 服务器启动失败"
    tail -10 /tmp/trae-reset.log
fi