# Shared paths and helpers for RBS scripts.
# shellcheck shell=bash

_lm_lib_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LM_ROOT="$(cd "$_lm_lib_dir/../.." && pwd)"
LM_SCRIPTS="$(cd "$_lm_lib_dir/.." && pwd)"
LM_CONTAINER="${LM_CONTAINER:-lidar-manager-limited}"
LM_URL="${LM_URL:-http://127.0.0.1:8080}"
LM_TEST_PORT="${LM_TEST_PORT:-18080}"

wait_for_health() {
  local base="${1:-$LM_URL}"
  local tries="${2:-40}"
  local i
  for ((i = 1; i <= tries; i++)); do
    if curl -sf "${base}/api/health" >/dev/null 2>&1; then
      return 0
    fi
    sleep 0.5
  done
  return 1
}

free_port() {
  local port="$1"
  if command -v fuser >/dev/null 2>&1; then
    fuser -k "${port}/tcp" 2>/dev/null || true
  elif command -v lsof >/dev/null 2>&1; then
    local pids
    pids="$(lsof -ti "tcp:${port}" 2>/dev/null || true)"
    [[ -n "$pids" ]] && kill $pids 2>/dev/null || true
  fi
}
