#!/bin/bash
# OpenClaw LingClaw Browser 一键安装脚本
# 适用于 Ubuntu/Debian 系统

set -e

echo "🚀 LingClaw Browser 安装脚本"
echo "=============================="

# 检查 root 权限
if [ "$EUID" -eq 0 ]; then 
   echo "⚠️  请不要使用 root 运行此脚本"
   exit 1
fi

# 配置变量
INSTALL_DIR="/opt/lingclaw-browser"
DATA_DIR="$INSTALL_DIR/data"
CDP_PORT="18900"
SERVICE_NAME="lingclaw-chrome"

# 1. 安装依赖
echo "📦 步骤 1/7: 安装系统依赖..."
sudo apt-get update -qq
sudo apt-get install -y -qq fonts-noto-cjk fonts-noto-cjk-extra xdg-utils curl jq 2>/dev/null || {
    echo "⚠️  部分包安装失败，尝试继续..."
}

# 2. 安装/检查 Chromium
echo "🔍 步骤 2/7: 检查并安装 Chromium 浏览器..."
if ! command -v chromium-browser &> /dev/null; then
    echo "📥 Chromium 未安装，正在安装..."
    sudo apt-get install -y -qq chromium-browser || {
        echo "⚠️  apt 安装失败，尝试使用 snap..."
        sudo snap install chromium
    }
    
    # 再次检查
    if ! command -v chromium-browser &> /dev/null; then
        echo "❌ Chromium 安装失败"
        exit 1
    fi
fi
echo "✅ Chromium 已安装: $(chromium-browser --version 2>/dev/null | head -1)"

# 3. 创建目录
echo "📁 步骤 3/7: 创建数据目录..."
sudo mkdir -p "$DATA_DIR"
sudo chown -R "$USER:$USER" "$INSTALL_DIR"

# 4. 创建 systemd 服务文件
echo "📝 步骤 4/7: 创建 systemd 服务..."
sudo tee /etc/systemd/system/${SERVICE_NAME}.service > /dev/null <<EOF
[Unit]
Description=Headless Chrome with CDP for OpenClaw
After=network.target

[Service]
Type=simple
User=$USER
Group=$USER

# Chrome data directory
Environment="CHROME_DATA_DIR=$DATA_DIR"
Environment="CHROME_CDP_PORT=$CDP_PORT"

# Chrome executable (snap chromium)
Environment="CHROME_BIN=/usr/bin/chromium-browser"

# Working directory
WorkingDirectory=$INSTALL_DIR

# Run headless Chrome with CDP
ExecStart=/usr/bin/chromium-browser \\
    --headless=new \\
    --disable-gpu \\
    --window-size=1920,1080 \\
    --lang=zh-CN \\
    --accept-lang=zh-CN,en-US,en \\
    --user-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36" \\
    --no-sandbox \\
    --disable-dev-shm-usage \\
    --disable-setuid-sandbox \\
    --remote-debugging-address=0.0.0.0 \\
    --remote-debugging-port=$CDP_PORT \\
    --user-data-dir=$DATA_DIR \\
    --disable-background-networking \\
    --disable-background-timer-throttling \\
    --disable-client-side-phishing-detection \\
    --disable-default-apps \\
    --disable-extensions \\
    --disable-hang-monitor \\
    --disable-popup-blocking \\
    --disable-prompt-on-repost \\
    --disable-sync \\
    --metrics-recording-only \\
    --no-first-run \\
    --safebrowsing-disable-auto-update \\
    --disable-blink-features=AutomationControlled \\
    --password-store=basic \\
    --use-mock-keychain \\
    about:blank

# Restart policy
Restart=always
RestartSec=5

# Resource limits
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

# 5. 启动服务
echo "🚀 步骤 5/7: 启动 Chrome 服务..."
sudo systemctl daemon-reload
sudo systemctl start $SERVICE_NAME
sudo systemctl enable $SERVICE_NAME > /dev/null 2>&1

# 6. 等待服务启动并验证
echo "⏳ 步骤 6/7: 等待服务启动..."
sleep 3

for i in {1..10}; do
    if curl -s "http://localhost:$CDP_PORT/json/version" > /dev/null 2>&1; then
        echo "✅ Chrome CDP 服务已启动 (端口 $CDP_PORT)"
        break
    fi
    if [ $i -eq 10 ]; then
        echo "⚠️  服务启动超时，请手动检查: sudo systemctl status $SERVICE_NAME"
    fi
    sleep 1
done

# 7. 配置 OpenClaw
echo "⚙️  步骤 7/7: 配置 OpenClaw..."

# 检查 openclaw 命令
if command -v openclaw &> /dev/null; then
    # 设置 lingclaw profile
    openclaw config set browser.profiles.lingclaw "{\"color\":\"#00AA00\",\"cdpUrl\":\"http://localhost:$CDP_PORT\"}" --strict-json 2>/dev/null || {
        echo "⚠️  配置 profile 失败，可能需要手动配置"
    }
    
    # 设置默认 profile
    openclaw config set browser.defaultProfile lingclaw 2>/dev/null || {
        echo "⚠️  设置默认 profile 失败"
    }
    
    # 设置 attachOnly - 总是使用外部浏览器服务
    openclaw config set browser.attachOnly true 2>/dev/null || {
        echo "⚠️  设置 attachOnly 失败"
    }
    
    echo "✅ OpenClaw 配置完成"
    
    # 提示重启 gateway
    echo ""
    echo "🔄 请手动重启 OpenClaw Gateway 以应用配置:"
    echo "   openclaw gateway restart"
else
    echo "⚠️  未找到 openclaw 命令，跳过配置"
    echo "   请手动配置 ~/.openclaw/openclaw.json:"
    echo "   browser.profiles.lingclaw.cdpUrl = http://localhost:$CDP_PORT"
fi

# 完成
echo ""
echo "=============================="
echo "✅ 安装完成!"
echo ""
echo "📋 服务信息:"
echo "   服务名称: $SERVICE_NAME"
echo "   工作目录: $INSTALL_DIR"
echo "   数据目录: $DATA_DIR"
echo "   CDP 端口: $CDP_PORT"
echo "   CDP 地址: http://localhost:$CDP_PORT"
echo ""
echo "🔧 常用命令:"
echo "   查看状态: sudo systemctl status $SERVICE_NAME"
echo "   查看日志: sudo journalctl -u $SERVICE_NAME -f"
echo "   重启服务: sudo systemctl restart $SERVICE_NAME"
echo "   停止服务: sudo systemctl stop $SERVICE_NAME"
echo ""
echo "🧪 测试 CDP:"
echo "   curl http://localhost:$CDP_PORT/json/version"
echo ""
