#!/usr/bin/env bash
# start_sanad.sh — boot Sanad's main.py inside the gemini_sdk conda env.
#
# Used both manually (./start_sanad.sh) and from the systemd unit
# (sanad.service) for boot-time auto-start.
#
# Override knobs (env vars; all optional):
#   SANAD_HOME            project root (default ~/Sanad)
#   SANAD_CONDA_ENV       conda env name (default gemini_sdk)
#   SANAD_CONDA_BASE      conda install dir (default $HOME/miniconda3)
#   SANAD_DDS_INTERFACE   DDS network iface (default eth0)
#   SANAD_VOICE_BRAIN     gemini | local | model (default gemini)
#   SANAD_AUDIO_PROFILE   builtin | anker | hollyland_builtin (default builtin)
#   PORT                  dashboard port (default 8000)

set -u

SANAD_HOME="${SANAD_HOME:-$HOME/Sanad}"
SANAD_CONDA_ENV="${SANAD_CONDA_ENV:-gemini_sdk}"
SANAD_CONDA_BASE="${SANAD_CONDA_BASE:-$HOME/miniconda3}"

export SANAD_DDS_INTERFACE="${SANAD_DDS_INTERFACE:-eth0}"
export SANAD_VOICE_BRAIN="${SANAD_VOICE_BRAIN:-gemini}"
export SANAD_AUDIO_PROFILE="${SANAD_AUDIO_PROFILE:-builtin}"
export PORT="${PORT:-8000}"

# Mandatory environment fixes for Jetson + conda + Unitree SDK
export LD_PRELOAD="${LD_PRELOAD:-/usr/lib/aarch64-linux-gnu/libgomp.so.1}"
export PYTHONUNBUFFERED=1
# Optional: needed if/when the local pipeline imports CosyVoice
if [ -d "$HOME/CosyVoice" ]; then
  export PYTHONPATH="$HOME/CosyVoice:$HOME/CosyVoice/third_party/Matcha-TTS:${PYTHONPATH:-}"
fi

cd "$SANAD_HOME" || { echo "Sanad dir not found: $SANAD_HOME" >&2; exit 1; }

# Activate conda
if [ ! -f "$SANAD_CONDA_BASE/etc/profile.d/conda.sh" ]; then
  echo "Conda not found at $SANAD_CONDA_BASE — set SANAD_CONDA_BASE" >&2
  exit 1
fi
# shellcheck disable=SC1091
source "$SANAD_CONDA_BASE/etc/profile.d/conda.sh"
conda activate "$SANAD_CONDA_ENV" || {
  echo "Conda env '$SANAD_CONDA_ENV' activation failed" >&2
  exit 1
}

# Wait for the DDS interface to come up — robot may still be booting
for i in $(seq 1 20); do
  if ip link show "$SANAD_DDS_INTERFACE" 2>/dev/null | grep -q "state UP"; then
    break
  fi
  sleep 1
done

echo "[start_sanad] $(date) — launching main.py"
echo "[start_sanad]   SANAD_HOME=$SANAD_HOME"
echo "[start_sanad]   conda env=$SANAD_CONDA_ENV"
echo "[start_sanad]   DDS iface=$SANAD_DDS_INTERFACE"
echo "[start_sanad]   voice brain=$SANAD_VOICE_BRAIN  audio=$SANAD_AUDIO_PROFILE"
echo "[start_sanad]   port=$PORT"

exec python3 main.py --port "$PORT"
