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

BRIDGE_URL="https://ocb.ai-powered.ch"
INSTALL_TOKEN="${INSTALL_TOKEN:-}"
BOT_ID="${BOT_ID:-}"
BOT_PASSWORD="${BOT_PASSWORD:-}"
TENANT_ID="${TENANT_ID:-core}"
OPENCLAW_BIN="${OPENCLAW_BIN:-}"
OPENCLAW_PATH="${OPENCLAW_PATH:-}"

for cmd in curl jq openssl systemctl; do
  if ! command -v "${cmd}" >/dev/null 2>&1; then
    echo "Missing required command: ${cmd}"
    exit 1
  fi
done

if [ -z "${OPENCLAW_BIN}" ]; then
  for candidate in     "$(command -v openclaw || true)"     "$(command -v clawdbot || true)"     "/home/ubuntu/.npm-global/bin/openclaw"     "/home/ubuntu/.npm-global/bin/clawdbot"     "/usr/local/bin/openclaw"     "/usr/local/bin/clawdbot"     "/opt/homebrew/bin/openclaw"     "/opt/homebrew/bin/clawdbot"; do
    if [ -n "${candidate}" ] && [ -x "${candidate}" ]; then
      OPENCLAW_BIN="${candidate}"
      break
    fi
  done
fi

if [ -z "${OPENCLAW_BIN}" ]; then
  echo "Missing OpenClaw CLI (openclaw/clawdbot). Set OPENCLAW_BIN before running installer."
  exit 1
fi

if [ -z "${OPENCLAW_PATH}" ]; then
  OPENCLAW_PATH="$(dirname "${OPENCLAW_BIN}"):/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
fi

if [ -z "${BOT_ID}" ]; then
  if [ -f /home/ubuntu/.openclaw/workspace/IDENTITY.md ]; then
    BOT_ID="$(awk -F': ' 'tolower($0) ~ /name:/ {print $2; exit}' /home/ubuntu/.openclaw/workspace/IDENTITY.md | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9-' '-')"
    BOT_ID="openclaw-${BOT_ID:-agent}"
  else
    BOT_ID="openclaw-$(hostname | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9-' '-')"
  fi
fi

if [ -z "${BOT_PASSWORD}" ]; then
  BOT_PASSWORD="$(openssl rand -hex 16)"
fi

mkdir -p /etc/openclaw-bridge /opt/openclaw-bridge /var/log/openclaw-bridge

cat >/opt/openclaw-bridge/worker.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
source /etc/openclaw-bridge/bridge.env
export PATH="${OPENCLAW_PATH}"

while true; do
  curl -sS -N -u "${BOT_ID}:${BOT_PASSWORD}" "${BRIDGE_URL}/v1/stream?channel=inbox:${BOT_ID}" | while IFS= read -r line; do
    case "$line" in
      "data: "*)
        payload="${line#data: }"
        message_id="$(echo "$payload" | jq -r '.message_id // empty')"
        text="$(echo "$payload" | jq -r '.payload.text // .payload.message // "Bridge message received"')"
        if [ -n "${message_id}" ]; then
          if "${OPENCLAW_BIN}" system event --mode now --text "[BRIDGE][${BOT_ID}] ${text}" >/dev/null 2>&1; then
            jq -nc --arg message_id "${message_id}" '{message_id:$message_id}'               | curl -sS -u "${BOT_ID}:${BOT_PASSWORD}" -H 'content-type: application/json' -X POST "${BRIDGE_URL}/v1/ack" -d @- >/dev/null 2>&1 || true
          else
            echo "$(date -Is) WARN failed to dispatch local system event for ${message_id}" >&2
          fi
        fi
      ;;
    esac
  done
  sleep 2
done
EOF
chmod +x /opt/openclaw-bridge/worker.sh

cat >/etc/openclaw-bridge/bridge.env <<EOF
BRIDGE_URL=${BRIDGE_URL}
BOT_ID=${BOT_ID}
BOT_PASSWORD=${BOT_PASSWORD}
TENANT_ID=${TENANT_ID}
OPENCLAW_BIN=${OPENCLAW_BIN}
OPENCLAW_PATH=${OPENCLAW_PATH}
EOF
chmod 600 /etc/openclaw-bridge/bridge.env

cat >/usr/local/bin/ocb-send <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
source /etc/openclaw-bridge/bridge.env
TO="${1:-}"
TEXT="${2:-}"
if [ -z "${TO}" ] || [ -z "${TEXT}" ]; then
  echo "Usage: ocb-send <inbox:bot|topic:name> <text>"
  exit 1
fi
jq -nc --arg tenant_id "${TENANT_ID}" --arg from_bot "${BOT_ID}" --arg to "${TO}" --arg text "${TEXT}" '{tenant_id:$tenant_id,from_bot:$from_bot,to:$to,type:"notification",payload:{text:$text}}'   | curl -sS -u "${BOT_ID}:${BOT_PASSWORD}" -H 'content-type: application/json' -X POST "${BRIDGE_URL}/v1/messages" -d @- | jq .
EOF
chmod +x /usr/local/bin/ocb-send

cat >/etc/systemd/system/openclaw-bridge-worker.service <<'EOF'
[Unit]
Description=OpenClaw Bridge Worker
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
Environment=PATH=/home/ubuntu/.npm-global/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
ExecStart=/opt/openclaw-bridge/worker.sh
Restart=always
RestartSec=2

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now openclaw-bridge-worker.service

if [ -n "${INSTALL_TOKEN}" ]; then
  jq -nc --arg install_token "${INSTALL_TOKEN}" --arg bot_id "${BOT_ID}" --arg password "${BOT_PASSWORD}" --arg tenant_id "${TENANT_ID}" '{install_token:$install_token,bot_id:$bot_id,password:$password,tenant_id:$tenant_id}'     | curl -sS -X POST "${BRIDGE_URL}/v1/register" -H 'content-type: application/json' -d @- | jq .
else
  echo "WARN: INSTALL_TOKEN not provided; registration skipped"
fi

echo "Installed. Bot ID: ${BOT_ID}"
echo "Send test: ocb-send inbox:openclaw-sergio 'hello'"
