#!/usr/bin/env bash
# Pick processes via fzf, kill them. Default SIGTERM, override with first arg.
# Usage: fkill          # SIGTERM
#        fkill KILL     # SIGKILL
#        fkill 9        # SIGKILL (numeric)
set -eu

sig="${1:-TERM}"

pids=$(
  { printf '%-7s %-10s %5s %5s %10s  %s\n' PID USER %CPU %MEM ELAPSED COMMAND
    ps -eo pid,user,pcpu,pmem,etime,args --sort=-pcpu --no-headers \
      | awk -v me=$$ -v ppid=$PPID '$1 != me && $1 != ppid'
  } \
    | fzf --multi --header-lines=1 \
          --header='TAB multi-select, Enter to kill' \
          --preview='echo {}' --preview-window=down:3:wrap \
    | awk '{print $1}'
)

[[ -z "$pids" ]] && exit 0
echo "$pids" | xargs -r kill -"$sig"
