#!/usr/bin/env bash
# 停止仓库 GzWeb 仿真（释放 9002 与单实例锁）
set -euo pipefail

echo "[stop] stopping warehouse GzWeb services ..."

pkill -9 -f 'warehouse_foxglove_guard.sh' 2>/dev/null || true
pkill -9 -f 'warehouse_gzsim_keepalive.sh' 2>/dev/null || true
pkill -9 -f 'warehouse_gzweb.launch.py' 2>/dev/null || true
pkill -9 -f 'gz-launch.*websocket' 2>/dev/null || true
pkill -9 -f 'gz launch.*websocket' 2>/dev/null || true
pkill -9 -f 'foxglove_bridge' 2>/dev/null || true
pkill -9 -f 'gz sim' 2>/dev/null || true
pkill -9 -f 'robot_state_publisher' 2>/dev/null || true
sleep 1

pids="$(ss -ltnp 2>/dev/null | grep ':9002 ' | sed -E 's/.*pid=([0-9]+).*/\1/' | sort -u || true)"
if [[ -n "${pids}" ]]; then
  kill -9 ${pids} 2>/dev/null || true
fi

rm -f /tmp/warehouse_gzsim.lock
sleep 1

if ps aux | grep -E 'warehouse_gzweb|warehouse_foxglove|warehouse_gzsim_keepalive|gz-launch|gz sim' | grep -v grep >/dev/null; then
  echo "[stop] WARN: some processes may remain:"
  ps aux | grep -E 'warehouse_gzweb|warehouse_foxglove|warehouse_gzsim_keepalive|gz-launch|gz sim' | grep -v grep || true
  exit 1
fi

echo "[stop] done. 9002 free, lock removed. Now run: ./gzsim_run.sh"
