#!/usr/bin/env bash
# =============================================================================
# robot.sh — WORKSTATION-side helper: run manage.sh on the G1 robot (PC2) over SSH.
# manage.sh itself must run on the robot (that's where the hands live); this just
# forwards your command there.
#
#   ./robot.sh                      # robot status
#   ./robot.sh status|restart|...   # any manage.sh command (see: ./robot.sh help)
#   ./robot.sh like|handshake       # gestures (ARM MOVES on the robot)
#   ./robot.sh arm "shake hand"     # quotes/spaces preserved
#   ./robot.sh deploy               # rsync this repo -> robot, then build.sh
#
#   ./robot.sh -ip 10.255.254.88 status   # target a specific address (e.g. the
#                                         # wifi IP, which changes via DHCP)
#
# Env: ROBOT (default unitree@192.168.123.164 — ethernet). -ip overrides it.
#      Give -ip either "10.255.254.88" (user defaults to unitree) or "user@host".
# =============================================================================
set -euo pipefail

ROBOT="${ROBOT:-unitree@192.168.123.164}"

# -ip <addr> : target a specific host (e.g. the changing wifi IP) instead of eth0.
if [ "${1:-}" = "-ip" ] || [ "${1:-}" = "--ip" ]; then
  shift
  [ $# -ge 1 ] || { echo "usage: ./robot.sh -ip <addr> <command...>" >&2; exit 1; }
  case "$1" in *@*) ROBOT="$1" ;; *) ROBOT="unitree@$1" ;; esac
  shift
fi
HERE="$(cd "$(dirname "$0")" && pwd)"
REMOTE='~/DFX_inspire_service'
TT=""; [ -t 0 ] && TT="-t"   # allocate a TTY only when we have one (menu/pose/logs)
SSH_OPTS="-o ConnectTimeout=8"  # fail fast if eth0 is down (use -ip <wifi> instead)

echo ">> target: $ROBOT" >&2

if [ "${1:-}" = "deploy" ]; then
  echo ">> rsync $HERE -> $ROBOT:$REMOTE"
  rsync -az --exclude='build/' -e "ssh $SSH_OPTS" "$HERE/" "$ROBOT:$REMOTE/"
  # shellcheck disable=SC2086
  ssh $SSH_OPTS $TT "$ROBOT" "cd $REMOTE && ./build.sh"
  exit 0
fi

# shellcheck disable=SC2086
ssh $SSH_OPTS $TT "$ROBOT" "cd $REMOTE && ./manage.sh $(printf '%q ' "$@")"
