#!/bin/bash

set -eu -o pipefail

if [[ ${EUID} -ne 0 ]]; then
    echo "This script should be run as root." > /dev/stderr
    exit 1
fi

if [[ $# -eq 0 ]]; then
    echo "No arguments supplied"
    exit 1
fi

if [[ "$1" == "--check" ]]; then
    echo "OK"
    exit 0
fi

function killtree() {
    local pid=$1
    for cpid in $(pgrep -P "$pid"); do
        killtree "${cpid}" || true
    done
    echo "kill-child: killing $pid"
    kill -SIGTERM "${pid}" 2>/dev/null || true
    sleep 1
    kill -SIGKILL "${pid}" 2>/dev/null || true
}

readonly target_pid="$1"
readonly expected_parent_pid="$2"

readonly target_actual_parent_pid=$(ps -o ppid= -p "${target_pid}" 2>/dev/null | tr -d ' ')

if [[ -z "${target_actual_parent_pid}" ]]; then
  echo "kill-child: target PID ${target_pid} does not exist."
  exit 1
fi

if [[ "${target_actual_parent_pid}" -ne "${expected_parent_pid}" ]]; then
  echo "kill-child: refusing to kill — PID ${target_pid} is not a child of ${expected_parent_pid}."
  exit 1
fi

readonly child_cmd=$(ps -o cmd= -p "${target_pid}")
echo "kill-child: kill PID ${target_pid} (command: ${child_cmd})"
killtree ${target_pid}
