#!/usr/bin/env bash
set -euo pipefail

MODEL_DEFAULT="zai/glm-4.6v"
OPENCLAW_BIN="/usr/local/bin/openclaw"
AUTH_FILE="/root/.openclaw/agents/main/agent/auth-profiles.json"
SERVICE_FILE="/etc/systemd/system/openclaw-gateway.service"
TOKEN="${OPENCLAW_XIRANG_TOKEN:-}"
OPENCLAW_JSON="/root/.openclaw/openclaw.json"

log() { printf '[%s] %s\n' "$(date '+%F %T')" "$*"; }
err() { printf '[%s] ERROR: %s\n' "$(date '+%F %T')" "$*" >&2; }

if [[ "${EUID}" -ne 0 ]]; then
  err "Please run as root"
  exit 1
fi

if [[ -z "${TOKEN}" ]] && [[ -t 0 ]]; then
  read -r -s -p "Input xirang token (leave blank to skip model call validation): " TOKEN
  echo
fi

log "Install base packages"
dnf install -y curl tar xz git >/dev/null

log "Detect latest Node.js v22 from nodejs.org"
NODE_VERSION="$(curl -fsSL https://nodejs.org/dist/index.json | tr -d '\r' | grep -o '"version":"v22[^\"]*"' | head -n1 | cut -d'"' -f4)"
if [[ -z "${NODE_VERSION}" ]]; then
  err "Failed to detect Node.js v22 version"
  exit 1
fi

ARCH_RAW="$(uname -m)"
case "${ARCH_RAW}" in
  x86_64) NODE_ARCH="x64" ;;
  aarch64|arm64) NODE_ARCH="arm64" ;;
  *) err "Unsupported architecture: ${ARCH_RAW}"; exit 1 ;;
esac

log "Install Node.js ${NODE_VERSION} (${NODE_ARCH})"
cd /tmp
NODE_TAR="node-${NODE_VERSION}-linux-${NODE_ARCH}.tar.xz"
NODE_URL="https://nodejs.org/dist/${NODE_VERSION}/${NODE_TAR}"
curl -fsSLO "${NODE_URL}"
rm -rf /usr/local/nodejs
mkdir -p /usr/local/nodejs
tar -xJf "${NODE_TAR}" --strip-components=1 -C /usr/local/nodejs
ln -sf /usr/local/nodejs/bin/node /usr/local/bin/node
ln -sf /usr/local/nodejs/bin/npm /usr/local/bin/npm
ln -sf /usr/local/nodejs/bin/npx /usr/local/bin/npx
ln -sf /usr/local/nodejs/bin/corepack /usr/local/bin/corepack

log "Node/NPM"
node -v
npm -v

log "Install OpenClaw latest"
git config --global url."https://github.com/".insteadOf ssh://git@github.com/
git config --global url."https://github.com/".insteadOf git@github.com:
npm install -g openclaw@latest --unsafe-perm
ln -sf /usr/local/nodejs/bin/openclaw "${OPENCLAW_BIN}"
openclaw --version

mkdir -p "$(dirname "${AUTH_FILE}")"
if [[ -n "${TOKEN}" ]]; then
  log "Write auth profile with provided ZAI token"
  cat > "${AUTH_FILE}" <<JSON
{
  "version": 1,
  "profiles": {
    "ctyun:default": {
      "type": "token",
      "provider": "ctyun",
      "token": "${TOKEN}"
    }
  }
}
JSON
else
  if [[ ! -f "${AUTH_FILE}" ]]; then
    log "No token provided; create auth profile placeholder"
    cat > "${AUTH_FILE}" <<'JSON'
{
  "version": 1,
  "profiles": {
    "ctyun:default": {
      "type": "token",
      "provider": "ctyun",
      "token": ""
    }
  }
}
JSON
  else
    log "No token provided; keep existing auth profile"
  fi
fi
chmod 600 "${AUTH_FILE}"

log "Set model and gateway mode"
openclaw models set "${MODEL_DEFAULT}"
openclaw config set gateway.mode local

if systemctl --user show-environment >/dev/null 2>&1; then
  log "Use OpenClaw user-systemd service"
  openclaw gateway install
  openclaw gateway restart
else
  log "systemd --user unavailable; install system-level gateway service"
  cat > "${SERVICE_FILE}" <<'UNIT'
[Unit]
Description=OpenClaw Gateway (system)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
Environment=HOME=/root
Environment=PATH=/usr/local/bin:/usr/local/nodejs/bin:/usr/bin:/bin
ExecStart=/usr/local/bin/openclaw gateway
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
UNIT
  systemctl daemon-reload
  systemctl enable --now openclaw-gateway.service
fi

log "Runtime checks"
ss -ltnp | grep 18789 || true
openclaw models status --json || true
echo '' > "${OPENCLAW_JSON}"
cat > "${OPENCLAW_JSON}" <<JSON
{
    "models": {
        "mode": "merge",
        "providers": {
            "xirang": {
                "baseUrl": "https://wishub-x6.ctyun.cn/v1",
                "apiKey": "${TOKEN}",
                "api": "openai-completions",
                "models": [
                    {
                        "id": "GLM-5",
                        "name": "GLM-5",
                        "reasoning": true,
                        "input": ["text"],
                        "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
                        "contextWindow": 204800,
                        "maxTokens": 131072
                    },
                    {
                        "id": "Qwen3.5-397B-A17B",
                        "name": "Qwen3.5-397B-A17B",
                        "reasoning": true,
                        "input": ["text", "image"],
                        "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
                        "contextWindow": 65536,
                        "maxTokens": 16384
                    },
                    {
                        "id": "Qwen3-Max",
                        "name": "Qwen3-Max",
                        "reasoning": true,
                        "input": ["text"],
                        "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
                        "contextWindow": 258048,
                        "maxTokens": 65536
                    },
                    {
                        "id": "Doubao-Seed-2.0-pro",
                        "name": "Doubao-Seed-2.0-pro",
                        "reasoning": true,
                        "input": ["text"],
                        "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
                        "contextWindow": 131072,
                        "maxTokens": 65536
                    },
                    {
                        "id": "DeepSeek-V3.2-Standard",
                        "name": "DeepSeek-V3.2-Standard",
                        "reasoning": true,
                        "input": ["text"],
                        "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
                        "contextWindow": 131072,
                        "maxTokens": 16384
                    },
                    {
                        "id": "DeepSeek-V3-0324",
                        "name": "DeepSeek-V3-0324",
                        "reasoning": true,
                        "input": ["text"],
                        "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
                        "contextWindow": 131072,
                        "maxTokens": 16384
                    },
                    {
                        "id": "Kimi-K2-Thinking",
                        "name": "Kimi-K2-Thinking",
                        "reasoning": true,
                        "input": ["text"],
                        "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
                        "contextWindow": 32768,
                        "maxTokens": 16384
                    },
                    {
                        "id": "DeepSeek-R1-0528",
                        "name": "DeepSeek-R1-0528",
                        "reasoning": true,
                        "input": ["text"],
                        "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
                        "contextWindow": 98304,
                        "maxTokens": 16384
                    }
                ]
            }
        }
    },
    "agents": {
        "defaults": {
            "model": {
                "primary": "xirang/GLM-5"
            },
            "models": {
                "xirang/GLM-5": {},
                "xirang/Qwen3.5-397B-A17B": {},
                "xirang/Qwen3-Max": {},
                "xirang/Doubao-Seed-2.0-pro": {},
                "xirang/DeepSeek-V3.2-Standard": {},
                "xirang/DeepSeek-V3-0324": {},
                "xirang/Kimi-K2-Thinking": {},
                "xirang/DeepSeek-R1-0528": {}
            }
        }
    },
    "gateway": {
        "mode": "local"
    }
}
JSON
openclaw gateway restart
if ! systemctl restart openclaw-gateway.service; then
    log "【警告】openclaw-gateway 重启失败，跳过并继续执行脚本(openclaw gateway restart执行成功可忽略)"
fi
if [[ -n "${TOKEN}" ]]; then
  log "Agent smoke test"
  openclaw agent --local --agent main -m "请仅回复OK" --json
else
  log "Skip agent smoke test: TOKEN is empty"
fi

log "Done"
