#!/usr/bin/env bash
# Launch the MuJoCo viewer on the smith300 robot.
#
# Usage:
#   ./view_robot.sh                 # uses example_twolink.xml in this folder
#   ./view_robot.sh path/to/x.xml   # any other MJCF
#
# Override the python interpreter via PYTHON=... if mjpython isn't on PATH:
#   PYTHON=/opt/homebrew/bin/python3.11 ./view_robot.sh
#
# Note: on macOS the interactive viewer needs `mjpython` (not plain python3),
# otherwise the GL context can't be created from a background thread.

set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$DIR"

XML="${1:-example_twolink.xml}"

pick_python() {
  if [[ -n "${PYTHON:-}" ]]; then
    echo "${PYTHON}"
    return 0
  fi
  for c in mjpython /opt/homebrew/bin/mjpython python3.11 /opt/homebrew/bin/python3.11 python3 python; do
    if command -v "${c}" >/dev/null 2>&1; then
      echo "${c}"
      return 0
    fi
  done
  echo "No python/mjpython found on PATH; set PYTHON=..." >&2
  exit 1
}

PY="$(pick_python)"
exec "${PY}" -m mujoco.viewer --mjcf "${XML}"
