#!/usr/bin/env bash
# Agente Pessoal Kit — bootstrap da base numa VPS Ubuntu (ou máquina Linux) limpa.
# Instala OpenClaw + Node + serviço systemd + religador. Rodar como root.
set -euo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
OPENCLAW_VERSION="${OPENCLAW_VERSION:-2026.6.8}"
WS="$HOME/.openclaw"

echo "==> [1/7] Pacotes base"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y curl git jq ffmpeg python3 python3-pip

echo "==> [2/7] Node 22 (nvm)"
if [ ! -d "$HOME/.nvm" ]; then
  curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
fi
export NVM_DIR="$HOME/.nvm"; . "$NVM_DIR/nvm.sh"
nvm install 22 && nvm use 22 && nvm alias default 22
ln -sf "$(command -v node)" /usr/local/bin/node || true
ln -sf "$(command -v npm)"  /usr/local/bin/npm  || true

echo "==> [3/7] OpenClaw ${OPENCLAW_VERSION}"
npm i -g "openclaw@${OPENCLAW_VERSION}"
ln -sf "$(command -v openclaw)" /usr/local/bin/openclaw || true
openclaw --version

echo "==> [4/7] Init config + workspace"
openclaw setup --non-interactive --accept-risk --workspace "$WS/workspace" || true
mkdir -p "$WS"

echo "==> [5/7] .env"
touch "$WS/.env"; chmod 600 "$WS/.env"
grep -q '^TELEGRAM_BOT_TOKEN=' "$WS/.env" || echo 'TELEGRAM_BOT_TOKEN=' >> "$WS/.env"
grep -q '^GATEWAY_AUTH_TOKEN=' "$WS/.env" || echo "GATEWAY_AUTH_TOKEN=$(openssl rand -hex 24)" >> "$WS/.env"

echo "==> [6/7] Serviço systemd"
cat > /etc/systemd/system/openclaw-gateway.service <<UNIT
[Unit]
Description=OpenClaw Gateway
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=$WS
EnvironmentFile=-$WS/.env
ExecStart=/usr/local/bin/openclaw gateway run --force
Restart=always
RestartSec=10
TimeoutStopSec=15
ProtectSystem=full
ProtectHome=false
NoNewPrivileges=true
PrivateTmp=true
LimitNOFILE=65536

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

echo "==> [7/7] Religador (vigia que religa o agente se cair ou travar)"
bash "$DIR/setup-religador.sh"

echo "BASE PRONTA."
