#!/usr/bin/env bash
# Run the containerized hand stack (service + bridge + dashboard).
# Stops any host-native inspire_g1/bridge first — two services would collide on
# the RS-485 bus. Needs --network host (DDS) + --privileged -v /dev:/dev (serial).
set -e
IMG="${IMG:-inspire-hand:latest}"
IFACE="${IFACE:-eth0}"

echo ">> removing old container, then killing host-native services (avoid double inspire_g1)"
docker rm -f inspire-hand 2>/dev/null || true          # kill container's procs first
pkill -x inspire_g1  2>/dev/null || true               # now only host natives remain
pkill -x hand_bridge 2>/dev/null || true
pkill -f hand_web.py 2>/dev/null || true
sleep 1; pkill -9 -x inspire_g1 2>/dev/null || true

# INSPIRE_RIGHT_PATH pins which physical USB socket is the RIGHT hand. Both hands answer on
# RS-485 id 1, so without this the side is inferred from USB path ORDER — correct today, but
# it would flip undetected if the two dongles were swapped between sockets.
# Operator-verified at the robot 2026-08-03: usb 1-2.2.1.1 is the physical RIGHT hand.
# (An earlier wiggle test concluded the opposite; the operator watching the robot corrected
# it. Flip this one value if the sides ever read swapped again — nothing else needs changing.)
RIGHT_PATH="${INSPIRE_RIGHT_PATH:-1-2.2.1.1}"
# Saved shapes/combos on the HOST, so rebuilding the image no longer wipes the library.
DATA_DIR="${HAND_DATA_DIR:-$HOME/hand_data}"
# Recordings live on the HOST for the same reason the shape library does: a `docker rm -f`
# in this script would otherwise destroy every take ever made.
mkdir -p "$DATA_DIR" "$DATA_DIR/DataG1"

# always: the hands must be there whenever the robot is, and the Sanad "Hands" tab proxies to
# this stack — a robot that boots without it shows an OFFLINE banner until someone SSHes in.
# `always` rather than `unless-stopped` so it also comes back after a manual `docker stop`,
# not just after a reboot. Note the trade-off: this stack takes the RS-485 bus and
# rt/inspire/cmd as soon as it starts. `./start.sh stop` still removes it (rm -f), and it
# stays gone until the next ./start.sh.
docker run -d --name inspire-hand --restart always \
  --network host --privileged -v /dev:/dev \
  -v "$DATA_DIR":/opt/hand/data \
  -v "$DATA_DIR/DataG1":/opt/recorder/DataG1 \
  -e HAND_DATA=/opt/hand/data \
  -e INSPIRE_RIGHT_PATH="$RIGHT_PATH" \
  -e IFACE="$IFACE" "$IMG"
echo ">> right hand pinned to usb $RIGHT_PATH   ·   data dir $DATA_DIR   ·   takes $DATA_DIR/DataG1"

sleep 4
docker logs --tail 24 inspire-hand || true
echo ">> inspire_g1 instances (want 1, the container's): $(pgrep -xc inspire_g1)"
ip=$(hostname -I | awk '{print $1}')
echo ">> dashboard: http://$ip:8088"
