#!/usr/bin/env bash
# Ubuntu/Linux: terminate any process whose command line contains "AIDriverEEBackend".
set -euo pipefail

PATTERN="AIDriverEEBackend"

# Exclude this shell and its parent — the script filename contains the same substring.
list_target_pids() {
  local out="" c
  for c in $(pgrep -f "$PATTERN" 2>/dev/null || true); do
    if [[ "$c" != "$$" && "$c" != "$PPID" ]]; then
      out="${out:+$out }$c"
    fi
  done
  echo "$out"
}

pids=$(list_target_pids)

if [[ -z "$pids" ]]; then
  echo "No process found matching: $PATTERN"
  exit 0
fi

echo "Found PID(s): $pids"
echo "Sending SIGTERM..."
kill -TERM $pids 2>/dev/null || true

sleep 2

still=$(list_target_pids)
if [[ -n "$still" ]]; then
  echo "Still running, sending SIGKILL: $still"
  kill -KILL $still 2>/dev/null || true
fi

sleep 1
left=$(list_target_pids)
if [[ -n "$left" ]]; then
  echo "Warning: process(es) still present: $left" >&2
  exit 1
fi

echo "Done."
