#!/usr/bin/env bash
# GzWeb 仓库场景 — Gazebo Sim + gz-launch :9002（GzWeb 连 wss://同域/gzbridge/）
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

sleep 3
export PATH="/usr/bin:/bin:/opt/ros/humble/bin:${PATH}"
export LIBGL_ALWAYS_SOFTWARE=1
export QT_QPA_PLATFORM=offscreen
set +u
source /opt/ros/humble/setup.bash
[[ -f "${ROOT}/install/setup.bash" ]] && source "${ROOT}/install/setup.bash"
set -u

LOG_DIR="${ROOT}/autorun_logs/autorun_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$LOG_DIR"

pkill -f 'gz launch.*websocket' 2>/dev/null || true
pkill -f 'gz-launch.*websocket' 2>/dev/null || true
sleep 1

echo "[autorun] launching warehouse Gazebo Sim ..."
ros2 launch bcr_bot gz.launch.py > "${LOG_DIR}/warehouse_gzsim.log" 2>&1 &
GZSIM_PID=$!

sleep 15
if ! ps -p "$GZSIM_PID" > /dev/null; then
  echo "[autorun] Gazebo exited early:"
  tail -40 "${LOG_DIR}/warehouse_gzsim.log" || true
  exit 1
fi

echo "[autorun] starting visual topic classifier ..."
ros2 run bcr_bot visual_topic_classifier.py > "${LOG_DIR}/visual_topic_classifier.log" 2>&1 &
CLASSIFIER_PID=$!

sleep 2
if ! ps -p "$CLASSIFIER_PID" > /dev/null; then
  echo "[autorun] visual topic classifier exited early:"
  cat "${LOG_DIR}/visual_topic_classifier.log" || true
  exit 1
fi

WS_CONFIG="${ROOT}/src/websocket.gzlaunch"
[[ -f "$WS_CONFIG" ]] || WS_CONFIG="/usr/share/gz/gz-launch7/configs/websocket.gzlaunch"

# WebsocketServer is a separate process from ros2 launch — it does NOT inherit
# AppendEnvironmentVariable from warehouse_gzweb.launch.py. Without install/src
# on GZ_SIM_RESOURCE_PATH, mesh requests get "Access denied" and GzWeb stays empty.
export GZ_SIM_RESOURCE_PATH="${ROOT}/install:${ROOT}/src${GZ_SIM_RESOURCE_PATH:+:$GZ_SIM_RESOURCE_PATH}"
export IGN_GAZEBO_RESOURCE_PATH="${GZ_SIM_RESOURCE_PATH}"

echo "[autorun] starting gz-launch websocket on :9002 ..."
echo "[autorun] GZ_SIM_RESOURCE_PATH=${GZ_SIM_RESOURCE_PATH}"
gz launch "$WS_CONFIG" > "${LOG_DIR}/websocket.log" 2>&1 &
WEBSOCKET_PID=$!

sleep 10
if ! ps -p "$WEBSOCKET_PID" > /dev/null; then
  echo "[autorun] websocket exited:"
  cat "${LOG_DIR}/websocket.log" || true
  exit 1
fi

echo "[autorun] ready. Refresh GzWeb (wss://{host}/gzbridge/). logs: ${LOG_DIR}"
wait
