#!/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

# WebsocketServer asset whitelist (mesh under install/ share).
export GZ_SIM_RESOURCE_PATH="/workspace/install/bcr_bot/share/bcr_bot:/workspace/install:${GZ_SIM_RESOURCE_PATH:-}"

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 warehouse_gzweb.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

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

echo "[autorun] starting gz-launch websocket on :9002 ..."
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
