#!/usr/bin/env bash
# Vultr box (24/7, $18 tier): runs the Slack bot + OpenHands + the preview server. No GPU here —
# OpenHands only calls the remote LLM.
#
# TUNNEL DIRECTION CHANGED: the GPU is now an ON-PREM box behind office NAT, so it dials OUT to us
# (its onprem-tunnel.service publishes its vLLM as OUR 127.0.0.1:8000). We no longer run a tunnel
# service here — we just have to accept its SSH key. See step 7.
#
# Run as root on Vultr:  cd /srv/site-clones/slackbot && sudo bash infra/vultr-setup.sh
set -euo pipefail

echo "=== 1. System packages ==="
apt-get update
apt-get install -y software-properties-common
# OpenHands requires Python >=3.12; Ubuntu 22.04 ships 3.10, so add deadsnakes for 3.12.
add-apt-repository -y ppa:deadsnakes/ppa
apt-get update
apt-get install -y python3 python3-venv python3-pip git wget curl autossh python3.12 python3.12-venv \
                   fonts-dejavu-core   # bold font used by the make_logo wordmark generator

echo "=== 2. Service user + secret dir ==="
id clonebot >/dev/null 2>&1 || useradd -m -s /bin/bash clonebot
mkdir -p /srv/slackbot   # holds .env only — secrets stay outside git
chown -R clonebot:clonebot /srv/site-clones

echo "=== 3. OpenHands (agent harness) in its own venv (/opt/openhands) — CPU only ==="
python3.12 -m venv /opt/openhands/venv     # OpenHands needs Python >=3.12
source /opt/openhands/venv/bin/activate
pip install --upgrade pip
# Pin the 0.x line: it has the headless CLI (python -m openhands.core.main) that clone_runner
# drives. The 1.x release is a programmatic SDK rewrite with no drop-in CLI — do NOT use it here.
pip install "openhands-ai==0.62.0"
deactivate
chown -R clonebot:clonebot /opt/openhands
# OpenHands 0.62 LocalRuntime starts a Playwright/Chromium browser env at startup, so the
# browser must be installed (or the runtime server crashes with Connection refused).
/opt/openhands/venv/bin/playwright install-deps chromium || true
sudo -u clonebot /opt/openhands/venv/bin/playwright install chromium || true
# OpenHands runs as: python -m openhands.core.main (0.x headless). runtime="local" => runs
# commands directly here, no Docker. If LocalRuntime errors, set runtime="cli" in the config.

echo "=== 4. Slack bot venv + deps ==="
cd /srv/site-clones/slackbot
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
# rip.py renders landers with headless Chromium to capture post-JS content (Taboola-cloaked
# pages etc.) — the browser binary is separate from the pip package and must be installed here too.
playwright install-deps chromium || true
deactivate
sudo -u clonebot venv/bin/playwright install chromium || true

echo "=== 5. Accept the ON-PREM box's reverse tunnel ==="
# The on-prem GPU box dials IN and publishes its vLLM as our 127.0.0.1:8000, so we run no tunnel
# service here — we only authorize its key. Run gpu-setup.sh on the on-prem box first; it prints
# an ed25519 pubkey. Paste that key here:
install -d -m 700 -o clonebot -g clonebot /home/clonebot/.ssh
touch /home/clonebot/.ssh/authorized_keys
chown clonebot:clonebot /home/clonebot/.ssh/authorized_keys
chmod 600 /home/clonebot/.ssh/authorized_keys
echo "    >>> Append the ON-PREM box's pubkey to /home/clonebot/.ssh/authorized_keys"
# Keep dropped reverse tunnels from leaving a stale :8000 bound (which makes autossh's
# ExitOnForwardFailure loop forever).
if ! grep -q '^ClientAliveInterval' /etc/ssh/sshd_config; then
  printf '\nClientAliveInterval 30\nClientAliveCountMax 3\n' >> /etc/ssh/sshd_config
  systemctl reload ssh || systemctl reload sshd || true
fi

echo "=== 6. .env ==="
if [ ! -f /srv/slackbot/.env ]; then
  cp /srv/site-clones/slackbot/.env.example /srv/slackbot/.env
  echo "    >>> Edit /srv/slackbot/.env: Slack tokens; set OPENHANDS_PYTHON=/opt/openhands/venv/bin/python"
  echo "        LLM_BASE_URL / PLANNER_BASE_URL stay http://127.0.0.1:8000/v1 (the reverse tunnel's end)."
fi

echo "=== 7. Install the bot service ==="
cp /srv/site-clones/slackbot/clonebot.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable clonebot

cat <<'EOF'

=== Vultr box done. Final steps ===
  1. On the ON-PREM box: run infra/gpu-setup.sh, then authorize its printed pubkey here
     (append to /home/clonebot/.ssh/authorized_keys).
  2. On the ON-PREM box: set VULTR_IP in onprem-tunnel.service, then: systemctl start onprem-tunnel
  3. Edit /srv/slackbot/.env (Slack tokens + OPENHANDS_PYTHON) BEFORE starting.
  4. Confirm the reverse tunnel reaches the on-prem model FROM HERE:
       curl -fsS http://127.0.0.1:8000/v1/models     (should list 'devstral' / 'qwen3-coder')
  5. systemctl start clonebot   &&   journalctl -u clonebot -f
EOF
