#!/usr/bin/env sh
set -eu

ROOT=${CLAWDBOX_AGENT_ROOT:-/data/agents/clawd}
LOG_DIR="$ROOT/logs"
PID_FILE="$LOG_DIR/node-host.pid"
LOG_FILE="$LOG_DIR/node-host.log"
OPENCLAW_DIR="$ROOT/tools/openclaw-node"
OPENCLAW_VERSION=${OPENCLAW_VERSION:-2026.7.2-beta.3}
DISPLAY_NAME=${CLAWDBOX_NODE_DISPLAY_NAME:-ClawdBox-CLI}
GATEWAY_HOST=${OPENCLAW_GATEWAY_HOST:-openclaw.apps.lab.apilab.us}
GATEWAY_PORT=${OPENCLAW_GATEWAY_PORT:-443}
NODE_HOME=${CLAWDBOX_NODE_HOME:-$ROOT/node-home}

export HOME="$NODE_HOME"
export OPENCLAW_STATE_DIR=${OPENCLAW_STATE_DIR:-$NODE_HOME/.openclaw}
export KUBECONFIG=${KUBECONFIG:-/home/claw/.kube/config}

mkdir -p "$ROOT/bin" "$ROOT/tools" "$LOG_DIR" "$OPENCLAW_DIR" "$HOME" "$OPENCLAW_STATE_DIR"

log() {
  printf '%s %s\n' "$(date -Iseconds)" "$*" | tee -a "$LOG_FILE"
}

if [ -f "$PID_FILE" ]; then
  old=$(cat "$PID_FILE" 2>/dev/null || true)
  case "$old" in
    *[!0-9]*|"") ;;
    *)
      if kill -0 "$old" 2>/dev/null; then
        echo "$DISPLAY_NAME already running: pid $old"
        exit 0
      fi
      ;;
  esac
fi

if [ ! -f "$OPENCLAW_DIR/package.json" ]; then
  cat > "$OPENCLAW_DIR/package.json" <<EOF
{
  "name": "clawdbox-openclaw-node",
  "private": true,
  "dependencies": {
    "openclaw": "$OPENCLAW_VERSION"
  }
}
EOF
fi

installed_version=""
if [ -f "$OPENCLAW_DIR/node_modules/openclaw/package.json" ]; then
  installed_version=$(node -p "require('$OPENCLAW_DIR/node_modules/openclaw/package.json').version" 2>/dev/null || true)
fi

if [ "$installed_version" != "$OPENCLAW_VERSION" ]; then
  log "Installing openclaw@$OPENCLAW_VERSION under $OPENCLAW_DIR"
  npm install --prefix "$OPENCLAW_DIR" "openclaw@$OPENCLAW_VERSION" --omit=dev >> "$LOG_FILE" 2>&1
fi

OPENCLAW_BIN="$OPENCLAW_DIR/node_modules/.bin/openclaw"
if [ ! -x "$OPENCLAW_BIN" ]; then
  log "OpenClaw binary not found at $OPENCLAW_BIN"
  exit 1
fi
ln -sf "$OPENCLAW_BIN" "$ROOT/bin/openclaw"

TOKEN=${OPENCLAW_GATEWAY_TOKEN:-}
if [ -z "$TOKEN" ]; then
  TOKEN=$(oc get deployment openclaw -n openclaw -o jsonpath='{.spec.template.spec.containers[0].env[?(@.name=="OPENCLAW_GATEWAY_TOKEN")].value}' 2>/dev/null || true)
fi
if [ -z "$TOKEN" ]; then
  log "OPENCLAW_GATEWAY_TOKEN is unavailable; skipping node-host startup"
  exit 1
fi

TLS_FLAG=""
if [ "${OPENCLAW_GATEWAY_TLS:-true}" = "true" ]; then
  TLS_FLAG="--tls"
fi

log "Starting $DISPLAY_NAME against $GATEWAY_HOST:$GATEWAY_PORT"
OPENCLAW_GATEWAY_TOKEN="$TOKEN" nohup "$OPENCLAW_BIN" node run \
  --display-name "$DISPLAY_NAME" \
  --host "$GATEWAY_HOST" \
  --port "$GATEWAY_PORT" \
  $TLS_FLAG >> "$LOG_FILE" 2>&1 &
echo $! > "$PID_FILE"
sleep 1
echo "Started $DISPLAY_NAME node host: pid $(cat "$PID_FILE")"
