#!/bin/bash
# OpenClaw（龙虾）本地安装脚本
# 适用于 Ubuntu 系统（主机或 Docker 内）

set -e

HOME_DIR=$(eval echo ~)
echo "当前用户 HOME 目录: $HOME_DIR"

echo "=== [1/6] 安装基础依赖 ==="
apt update
apt-get install -y curl ssh vim gcc cmake build-essential git sudo

echo "=== [2/6] 安装 Node.js LTS ==="
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
node -v
npm -v
npm install -g pnpm
pnpm -v

echo "=== [3/6] 下载 OpenClaw 源码 ==="
mkdir -p "$HOME_DIR/project"
cd "$HOME_DIR/project"
if [ ! -d "openclaw" ]; then
  git clone https://gitee.com/fgai/openclaw.git \
    || git clone https://ghfast.top/https://github.com/openclaw/openclaw.git \
    || https://github.com/openclaw/openclaw.git
fi
cd "$HOME_DIR/project/openclaw"

echo "=== [4/6] 安装依赖并构建 ==="
pnpm install
pnpm ui:build
pnpm build

echo "=== [5/6] 全局链接 OpenClaw ==="
cd "$HOME_DIR/project/openclaw"
export SHELL="/bin/bash"
pnpm setup
PNPM_GLOBAL_BIN=$(pnpm bin -g)
export PNPM_HOME="$HOME_DIR/.local/share/pnpm"
export PATH="$PNPM_HOME:$PNPM_GLOBAL_BIN:$PATH"
echo "PNPM_HOME 已设置: $PNPM_HOME"
bash -c "source ~/.bashrc; echo 'bashrc 加载完成'"
cd "$HOME_DIR/project/openclaw"
pnpm link --global


echo "=== 配置 openclaw.json ==="
CONFIG_DIR="$HOME_DIR/.openclaw"
CONFIG_FILE="$CONFIG_DIR/openclaw.json"
mkdir -p "$CONFIG_DIR"
chmod -R 777 "$CONFIG_DIR"

# 备份已有配置
if [ -f "$CONFIG_FILE" ]; then
  cp "$CONFIG_FILE" "${CONFIG_FILE}.bak.$(date +%Y%m%d_%H%M%S)"
  echo "已备份原配置：${CONFIG_FILE}.bak.*"
fi

cat > "$CONFIG_FILE" << EOF
{
  "models": {
    "mode": "merge",
    "providers": {
      "custom-001": {
        "baseUrl": "http://xxxxx/v1",
        "apiKey": "xxxxx",
        "api": "openai-completions",
        "models": [
          {
            "id": "qwen-plus",
            "name": "qwen-plus (Custom Provider)",
            "reasoning": false,
            "input": [
              "text"
            ],
            "cost": {
              "input": 0,
              "output": 0,
              "cacheRead": 0,
              "cacheWrite": 0
            }
          }
        ]
      }
    }
  },
  "agents": {
    "defaults": {
      "model": {
        "primary": "custom-001/qwen-plus"
      },
      "models": {
        "custom-001/qwen-plus": {}
      },
      "workspace": "$HOME_DIR/.openclaw/workspace"
    }
  },
  "tools": {
    "profile": "coding",
    "web": {
      "search": {
        "enabled": true,
        "provider": "gemini",
        "gemini": {
          "apiKey": "sk-xxxxxxxxxx"
        }
      }
    }
  },
  "commands": {
    "native": "auto",
    "nativeSkills": "auto",
    "restart": true,
    "ownerDisplay": "raw"
  },
  "session": {
    "dmScope": "per-channel-peer"
  },
  "hooks": {
    "internal": {
      "enabled": true,
      "entries": {
        "boot-md": {
          "enabled": true
        },
        "bootstrap-extra-files": {
          "enabled": true
        },
        "command-logger": {
          "enabled": true
        },
        "session-memory": {
          "enabled": true
        }
      }
    }
  },
  "gateway": {
    "port": 18789,
    "mode": "local",
    "bind": "loopback",
    "auth": {
      "mode": "token",
      "token": ""
    },
    "tailscale": {
      "mode": "off",
      "resetOnExit": false
    },
    "controlUi": {
    allowedOrigins: ["http://localhost:18789"],
    },
    "nodes": {
      "denyCommands": [
        "camera.snap",
        "camera.clip",
        "screen.record",
        "contacts.add",
        "calendar.add",
        "reminders.add",
        "sms.send"
      ]
    }
  },
  "skills": {
    "install": {
      "nodeManager": "npm"
    },
    "entries": {
      "goplaces": {
        "apiKey": "sk-xxxxxxxxxxxxxx"
      },
      "nano-banana-pro": {
        "apiKey": "sk-xxxxxxxxxxxxxxxxxxxxx"
      },
      "notion": {
        "apiKey": "sk-xxxxxxxxxxxxxxxxxxxx"
      },
      "openai-image-gen": {
        "apiKey": "sk-xxxxxxxxxxxxxxxxxxxxx"
      },
      "openai-whisper-api": {
        "apiKey": "sk-xxxxxxxxxxxxxxxxxxxx"
      },
      "sag": {
        "apiKey": "sk-xxxxxxxxxxxxxxxxxxxxx"
      }
    }
  }
}
EOF

echo "=== 安装插件 ==="
openclaw plugins install @wecom/wecom-openclaw-plugin@1.0.6


echo "=== [6/6] 安装龙虾配置助手 ==="
cd "$HOME_DIR/project"
git clone https://gitee.com/fgai/claw-helper.git
cd "$HOME_DIR/project/claw-helper"
cp .env.example .env
npm install
nohup npm run dev > /tmp/claw-helper-dev.log 2>&1 &
echo $! > /tmp/claw-helper-dev.pid
echo "龙虾配置助手已在后台启动，日志：/tmp/claw-helper-dev.log"

echo ""
echo "=== 安装完成 ==="
echo "配置文件已写入：$CONFIG_FILE"

bash -c "source ~/.bashrc; echo 'bashrc 加载完成'"
