#!/usr/bin/ruby.ruby3.4 

def find_pry_rescuers extra_id = ''
  pattern = 'pry-rescue @.*' + extra_id
  pids = nil
  IO.popen ['pgrep', '-f', pattern] do |io|
    pids = io.readlines.map &:to_i
  end
  pids
end

if %w(-h --help').include? ARGV[0]
  warn %{
#$0 - Stops a pry-rescuer

By default gets all of them, but if you provide an arg, it can filter by the
directory name.

Uses SIGINT by default, unless you supply the -9 option.

Currently running pry-rescue pids: #{find_pry_rescuers.join ' '}}
  exit 1
end

signal =
  if ARGV.delete '-9'
    :KILL
  else
    :INT
  end

pids = find_pry_rescuers(ARGV.join ' ')
warn '(No processes found.)' if pids.size.zero?
pids.each do |pid|
  warn "Killing #{pid} with SIG#{signal}."
  Process.kill signal, pid
end
