#!/usr/bin/env bash
# One-shot build + run of SanadR1 in Docker on the R1 backpack.
# Also disables the old conda systemd service so :8001 doesn't collide.
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$HERE"

if [ ! -f .env ]; then
  echo "!! docker/.env missing — copy .env.example to .env and set SANAD_GEMINI_API_KEY" >&2
  exit 1
fi

# Old conda-based service (if present) would fight for port 8001.
if systemctl list-unit-files 2>/dev/null | grep -q '^sanadr1\.service'; then
  echo ">> stopping + disabling the old conda sanadr1.service"
  sudo systemctl disable --now sanadr1.service || true
fi

echo ">> building image (CycloneDDS compiles from source — first build is slow)"
docker compose build

echo ">> starting container (host network, auto-restart)"
docker compose up -d

echo ">> waiting for the dashboard..."
for i in $(seq 1 30); do
  if curl -fsS http://127.0.0.1:8001/ >/dev/null 2>&1; then
    echo ">> UP: dashboard on :8001"
    docker compose ps
    exit 0
  fi
  sleep 2
done
echo "!! dashboard did not answer in 60s — check: docker compose logs -f" >&2
docker compose logs --tail=40
exit 1
