#!/bin/sh
# Tested against busybox v1.20.2.
# Steven Bromley

set -u

killtree() {
  local parent=$1 signal=$2
  
  # Stop parent to prevent more children being created
  kill -STOP $parent
  
  for child in $(pgrep -P $parent); do
    killtree $child $signal
  done
  
  # Send signal to parent, then continue - order is important
  kill -$signal $parent
  kill -CONT $parent
}

case "${1:-help}" in
  *[!0-9]*|"")
    echo -e >&2 \
      "Usage: $(basename $0) PID [SIGNAL]\n"\
      "\nSend a signal to the specified process and all it's children."\
      "\nIf signal is unspecified, send SIGTERM.\n"
    exit 1
    ;;
  *)
    killtree $1 ${2:-TERM}
    ;;
esac
