#!/bin/bash



set -e



RELAY_URL="https://www.woooooow.online"

RELAY_API_URL="https://relay.woooooow.online"

RELAY_SECRET="relay_secret_2026"

POLLER_DIR="$HOME/openclaw-relay"



echo "=== OpenClaw One-Click Installer ==="

echo ""



# 0. Install python3

if ! command -v python3 &>/dev/null; then

  echo "       Installing python3..."

  sudo apt-get update

  sudo apt-get install -y python3

  echo "✅ python3 installed"

else

  echo "✅ python3 already installed: $(python3 --version)"

fi



# 1. Install nvm + Node.js 24

if ! command -v node &>/dev/null; then

  echo "       Installing nvm and Node.js 24..."

  curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash

  export NVM_DIR="$HOME/.nvm"

  \. "$NVM_DIR/nvm.sh"

  nvm install 24

  echo "✅ Node.js $(node -v) installed"

else

  export NVM_DIR="$HOME/.nvm"

  [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

  echo "✅ Node.js already installed: $(node -v)"

fi



# 确保 nvm 永久生效

grep -q 'NVM_DIR' ~/.bashrc || {

  echo 'export NVM_DIR="$HOME/.nvm"' >> ~/.bashrc

  echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"' >> ~/.bashrc

}



# 2. Install git

if ! command -v git &>/dev/null; then

  echo "       Installing git..."

  sudo apt-get update

  sudo apt-get install -y git

  echo "✅ git installed"

else

  echo "✅ git already installed"

fi



# 3. Install OpenClaw

if ! command -v openclaw &>/dev/null; then

  echo "       Installing OpenClaw..."

  npm install -g openclaw

  echo "✅ OpenClaw installed"

else

  echo "✅ OpenClaw already installed"

fi



# 4. Install and configure gateway

echo "       Installing OpenClaw gateway..."

openclaw gateway install || true

openclaw config set gateway.mode local



# 5. Start OpenClaw gateway

echo "       Starting OpenClaw gateway..."

openclaw gateway start &

sleep 5



# 6. Register or login

read -p "Enter your username: " USERNAME

read -s -p "Enter your password: " PASSWORD

echo ""



REG_RES=$(curl -s --max-time 10 -X POST "$RELAY_API_URL/api/user/register" -H "Content-Type: application/json" -d "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}")

REG_SUCCESS=$(echo "$REG_RES" | grep -o '"success":true' || true)

REG_TAKEN=$(echo "$REG_RES" | grep -o 'Username taken' || true)



if [ -n "$REG_SUCCESS" ]; then

  echo "✅ Account created"

elif [ -n "$REG_TAKEN" ]; then

  echo "✅ Account exists, logging in..."

else

  echo "❌ Registration failed: $REG_RES"

  exit 1

fi



LOGIN_RES=$(curl -s --max-time 10 -X POST "$RELAY_API_URL/api/user/login" -H "Content-Type: application/json" -d "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}")



USER_ID=$(echo "$LOGIN_RES" | grep -o '"id":"[^"]*"' | grep -o '[^"]*"$' | tr -d '"')

USER_TOKEN=$(echo "$LOGIN_RES" | grep -o '"token":"[^"]*"' | grep -o '[^"]*"$' | tr -d '"')



if [ -z "$USER_ID" ] || [ -z "$USER_TOKEN" ]; then

  echo "❌ Login failed, please check your username and password"

  echo "Response: $LOGIN_RES"

  exit 1

fi



echo "✅ Login successful, userId: $USER_ID"



# 7. Get sub-key from relay server

KEY_RES=$(curl -s --max-time 10 "$RELAY_API_URL/api/user/apikey" -H "Authorization: Bearer $USER_TOKEN")



SUB_KEY=$(echo "$KEY_RES" | grep -o '"key":"[^"]*"' | grep -o '[^"]*"$' | tr -d '"')

BASE_URL=$(echo "$KEY_RES" | grep -o '"baseUrl":"[^"]*"' | grep -o '[^"]*"$' | tr -d '"')



if [ -z "$SUB_KEY" ]; then

  echo "❌ Failed to get API key"

  echo "Response: $KEY_RES"

  exit 1

fi



if [ -z "$BASE_URL" ]; then

  echo "❌ Failed to get baseUrl"

  echo "Response: $KEY_RES"

  exit 1

fi



echo "✅ API key retrieved"



# 8. Configure OpenClaw AI provider (minimal-change version, no full overwrite)

mkdir -p "$HOME/.openclaw"

CONFIG_FILE="$HOME/.openclaw/openclaw.json"



if [ ! -f "$CONFIG_FILE" ]; then

  echo '{}' > "$CONFIG_FILE"

fi



python3 - <<PY

import json

import os

from datetime import datetime, timezone



config_file = os.path.expanduser("$CONFIG_FILE")

base_url = """$BASE_URL""".rstrip("/")

sub_key = """$SUB_KEY"""



if not base_url.endswith("/v1"):

    base_url = base_url + "/v1"



if os.path.exists(config_file):

    with open(config_file, "r", encoding="utf-8") as f:

        try:

            data = json.load(f)

        except Exception:

            data = {}

else:

    data = {}



data.setdefault("meta", {})

data["meta"]["lastTouchedVersion"] = "2026.3.8"

data["meta"]["lastTouchedAt"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")



data.setdefault("auth", {})

data["auth"].setdefault("profiles", {})

data["auth"]["profiles"]["openai:manual"] = {

    "provider": "openai",

    "mode": "token"

}



data.setdefault("agents", {})

data["agents"].setdefault("defaults", {})

data["agents"]["defaults"]["model"] = {

    "primary": "oneapi/deepseek-chat"

}



data["agents"]["defaults"].setdefault("models", {})

data["agents"]["defaults"]["models"]["oneapi/deepseek-chat"] = {

    "alias": "DeepSeek Chat"

}

data["agents"]["defaults"]["models"]["oneapi/deepseek-reasoner"] = {

    "alias": "DeepSeek Reasoner"

}



data.setdefault("models", {})

data["models"].setdefault("providers", {})

data["models"]["providers"]["oneapi"] = {

    "baseUrl": base_url,

    "api": "openai-completions",

    "apiKey": sub_key,

    "models": [

        {

            "id": "deepseek-chat",

            "name": "deepseek-chat"

        },

        {

            "id": "deepseek-reasoner",

            "name": "deepseek-reasoner"

        }

    ]

}



data.setdefault("commands", {})

data["commands"].setdefault("native", "auto")

data["commands"].setdefault("nativeSkills", "auto")

data["commands"].setdefault("restart", True)

data["commands"].setdefault("ownerDisplay", "raw")



data.setdefault("gateway", {})

data["gateway"].setdefault("mode", "local")

data["gateway"].setdefault("auth", {})

data["gateway"]["auth"].setdefault("mode", "token")

data["gateway"]["auth"].setdefault("token", "")



with open(config_file, "w", encoding="utf-8") as f:

    json.dump(data, f, indent=2, ensure_ascii=False)

    f.write("\\n")

PY



echo "✅ AI provider configured"



# 设置默认模型

openclaw models set oneapi/deepseek-chat

echo "✅ Default model set to DeepSeek"



# 9. Get gateway token

sleep 2



GATEWAY_TOKEN=$(python3 - <<PY

import json, os

p = os.path.expanduser("$HOME/.openclaw/openclaw.json")

try:

    with open(p, "r", encoding="utf-8") as f:

        data = json.load(f)

    print(data.get("gateway", {}).get("auth", {}).get("token", ""))

except Exception:

    print("")

PY

)



if [ -z "$GATEWAY_TOKEN" ]; then

  echo "❌ Gateway token not found"

  exit 1

fi



echo "✅ Gateway token retrieved"



# 10. Download and configure poller

mkdir -p "$POLLER_DIR"



curl -s -o "$POLLER_DIR/poller.js" "$RELAY_URL/poller.js"

curl -s -o "$POLLER_DIR/package.json" "$RELAY_URL/package.json"



sed -i "s|userId: '[^']*'|userId: '$USER_ID'|g" "$POLLER_DIR/poller.js"

sed -i "s|gatewayToken: '[^']*'|gatewayToken: '$GATEWAY_TOKEN'|g" "$POLLER_DIR/poller.js"

sed -i "s|relayUrl: '[^']*'|relayUrl: '$RELAY_URL'|g" "$POLLER_DIR/poller.js"

sed -i "s|secret: '[^']*'|secret: '$RELAY_SECRET'|g" "$POLLER_DIR/poller.js"



OPENCLAW_PATH=$(which openclaw)

sed -i "s|execFile('[^']*openclaw'|execFile('$OPENCLAW_PATH'|g" "$POLLER_DIR/poller.js"

echo "✅ Poller configured"



# 11. Install dependencies

cd "$POLLER_DIR"

npm install 2>/dev/null || true

echo "✅ Dependencies installed"



# 12. Start poller in background

nohup node "$POLLER_DIR/poller.js" > "$POLLER_DIR/poller.log" 2>&1 &

echo "✅ Poller started (PID: $!)"



echo ""

echo "=== Setup complete! ==="

echo "OpenClaw is running and connected to $RELAY_URL"

echo "You can now use the control panel at $RELAY_URL/control.html"
