#!/usr/bin/env bash
# Run SanadR1 as a container on the backpack WITHOUT docker-compose (the backpack
# ships no compose plugin). This mirrors docker-compose.yml exactly. Idempotent:
# recreates the container from the already-loaded sanadr1:latest image.
#
#   cd ~/SanadR1/docker && ./run.sh
#
# Auto-start on boot is handled by --restart unless-stopped + the docker service.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

[ -f "$HERE/.env" ] || { echo "!! $HERE/.env missing (set SANAD_GEMINI_API_KEY)"; exit 1; }
docker image inspect sanadr1:latest >/dev/null 2>&1 || {
  echo "!! image sanadr1:latest not loaded — docker load < sanadr1-latest-arm64.tar.gz"; exit 1; }

# Pass the host's USB sound cards in when present (Anker/JBL-style external
# audio). gid 29 = the host 'audio' group that owns /dev/snd, so the in-container
# app user can reach it. Absent → the container runs DDS-audio-only as before.
SND_ARGS=()
if [ -e /dev/snd ]; then
  SND_ARGS=(--device /dev/snd --group-add 29)
  echo ">> /dev/snd found — enabling USB audio passthrough"
fi

# Robot DDS interface — portable across R1 backpacks. If .env pins one
# (install.sh writes the detected value there) we defer to it; otherwise
# auto-detect the NIC holding a 192.168.123.x address (the R1 internal net),
# falling back to eth10 (the standard EDU-backpack name). The entrypoint also
# defaults to eth10, so this is belt-and-suspenders.
IFACE_ARGS=()
if ! grep -q '^SANAD_DDS_INTERFACE=' "$HERE/.env" 2>/dev/null; then
  IFACE="$(ip -o -4 addr show 2>/dev/null | awk '$4 ~ /^192\.168\.123\./{print $2; exit}')"
  [ -n "$IFACE" ] || IFACE=eth10
  IFACE_ARGS=(-e "SANAD_DDS_INTERFACE=$IFACE")
  echo ">> DDS interface auto-detected: $IFACE"
fi

docker rm -f sanadr1 2>/dev/null || true
docker run -d --name sanadr1 \
  --network host \
  --restart unless-stopped \
  --env-file "$HERE/.env" \
  "${IFACE_ARGS[@]}" \
  -e SANAD_DASHBOARD_HOST=0.0.0.0 \
  -e SANAD_NAV_TOOLS=0 \
  -e SANAD_AUDIO_PROFILE=builtin \
  -e SANAD_VOICE_BRAIN=gemini \
  "${SND_ARGS[@]}" \
  -v sanadr1_data:/opt/SanadR1/data \
  -v sanadr1_logs:/opt/SanadR1/logs \
  sanadr1:latest

echo ">> started. logs: docker logs -f sanadr1   dashboard: http://<backpack-ip>:8001"
