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


ROOT="/workspace"

sleep 5

set +u
source /opt/ros/humble/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"

kill_port_listeners() {
  local port="$1"
  local pids
  pids="$(ss -ltnp 2>/dev/null | grep ":${port} " | sed -E 's/.*pid=([0-9]+).*/\1/' | sort -u || true)"
  if [[ -n "${pids}" ]]; then
    echo "[run_all] port ${port} already in use, killing: ${pids}"
    kill ${pids} 2>/dev/null || true
    sleep 1
  fi
}

kill_port_listeners 9002

export __NV_PRIME_RENDER_OFFLOAD=1
export __GLX_VENDOR_LIBRARY_NAME=nvidia
export TURTLEBOT3_MODEL=burger
ros2 launch turtlebot3_gazebo turtlebot3_office.launch.py > "${LOG_DIR}/tb3_gzsim.log" 2>&1 &
GZSIM_PID=$!
# gz sim -v 4 -s -r empty.sdf > "${LOG_DIR}/empty_gzsim.log" 2>&1 &
# GZSIM_PID=$!

echo "[autorun] tb3_gzsim pid=${GZSIM_PID}, log=${LOG_DIR}/tb3_gzsim.log"

sleep 8

if ps -p "$GZSIM_PID" > /dev/null; then
  echo "[autorun] tb3_gzsim is still running"
else
  echo "[autorun] tb3_gzsim exited early. Log:"
  cat "${LOG_DIR}/tb3_gzsim.log"
fi

echo "[autorun] starting websocket ..."

gz launch "${ROOT}/src/websocket.gzlaunch" > "${LOG_DIR}/websocket.log" 2>&1 &
WEBSOCKET_PID=$!

echo "[autorun] websocket pid=${WEBSOCKET_PID}, log=${LOG_DIR}/websocket.log"

sleep 10

if ps -p "$WEBSOCKET_PID" > /dev/null; then
  echo "[autorun] websocket is still running"
else
  echo "[autorun] websocket exited early. Log:"
  cat "${LOG_DIR}/websocket.log"
  exit 1
fi

echo "[autorun] all services started."
echo "[autorun] tb3_gzsim pid=${GZSIM_PID}"
echo "[autorun] websocket pid=${WEBSOCKET_PID}"

wait
