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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEFAULT_ROOT="/var/Galeria-ALPR-Control-Center"

if [[ -z "${INSTALL_ROOT:-}" ]]; then
  if [[ -d "$SCRIPT_DIR/server" ]]; then
    INSTALL_ROOT="$SCRIPT_DIR"
  else
    INSTALL_ROOT="$DEFAULT_ROOT"
  fi
fi

TARGETS=(
  "$INSTALL_ROOT/server"
  "$INSTALL_ROOT/web-admin"
)

echo "==> Looking for processes running under \"$INSTALL_ROOT\""
killed=0

for target in "${TARGETS[@]}"; do
  if [[ ! -d "$target" ]]; then
    continue
  fi

  while read -r pid; do
    [[ -z "$pid" ]] && continue
    if kill -0 "$pid" >/dev/null 2>&1; then
      echo "   -> Stopping PID $pid (match: $target)"
      kill "$pid" 2>/dev/null || true
      sleep 0.5
      if kill -0 "$pid" >/dev/null 2>&1; then
        echo "      PID $pid resisted, sending SIGKILL"
        kill -9 "$pid" 2>/dev/null || true
      fi
      killed=$((killed + 1))
    fi
  done < <(pgrep -f -- "$target" || true)
done

if [[ "$killed" -eq 0 ]]; then
  echo "No matching processes were found."
else
  echo "✅ Stopped $killed processes related to the Control Center."
fi
