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

PORT="${1:-16800}"

# Kill stale aria2 process bound to the target RPC port.
PIDS="$(lsof -nP -iTCP:"$PORT" -sTCP:LISTEN -t 2>/dev/null | sort -u || true)"
if [[ -z "$PIDS" ]]; then
  exit 0
fi

for pid in $PIDS; do
  cmd="$(ps -p "$pid" -o command= 2>/dev/null || true)"
  if [[ "$cmd" == *aria2c* ]]; then
    kill -15 "$pid" 2>/dev/null || true
  fi
done

sleep 0.3

PIDS="$(lsof -nP -iTCP:"$PORT" -sTCP:LISTEN -t 2>/dev/null | sort -u || true)"
if [[ -n "$PIDS" ]]; then
  for pid in $PIDS; do
    cmd="$(ps -p "$pid" -o command= 2>/dev/null || true)"
    if [[ "$cmd" == *aria2c* ]]; then
      kill -9 "$pid" 2>/dev/null || true
    fi
  done
fi
