#!/usr/bin/env bash
set -euo pipefail

# Stop all processes started by run_all.sh / run_ab.sh style workflow.

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

echo "[run_all_stop] stopping ROS/Gazebo workflow processes..."

# Launches / nodes
pkill -f "turtlebot3_office_gz.launch.py" 2>/dev/null || true
pkill -f "nav2_bringup navigation_launch.py" 2>/dev/null || true
pkill -f "nav2_bringup bringup_launch.py" 2>/dev/null || true
pkill -f "explore_lite explore.launch.py" 2>/dev/null || true
pkill -f "nav2_map_server map_saver_cli" 2>/dev/null || true

# Gazebo websocket and frontend
pkill -f "${ROOT}/websocket.sdf" 2>/dev/null || true
pkill -f "vite --host 0.0.0.0 --port 5173" 2>/dev/null || true
pkill -f "npm run dev:host" 2>/dev/null || true

# Gazebo processes usually started by ros_gz_sim / gz sim
pkill -f "ros_gz_sim" 2>/dev/null || true
pkill -f "gz sim" 2>/dev/null || true

# Free common ports if still occupied
for port in 5173 9002; do
  pids="$(ss -ltnp 2>/dev/null | grep ":${port} " | sed -E 's/.*pid=([0-9]+).*/\1/' | sort -u)"
  if [[ -n "${pids}" ]]; then
    echo "[run_all_stop] killing processes on port ${port}: ${pids}"
    kill ${pids} 2>/dev/null || true
  fi
done

echo "[run_all_stop] done."
