#!/bin/ksh

set -eu

usage() {
	echo "usage: robsd-kill -m mode" 1>&2
	exit 1
}

. "${EXECDIR:-/usr/local/libexec/robsd}/util.sh"
. "${EXECDIR:-/usr/local/libexec/robsd}/util-ports.sh"
. "${EXECDIR:-/usr/local/libexec/robsd}/util-regress.sh"

setprogname "robsd-kill"
[ "$(id -u)" -ne 0 ] && fatal "must be run as root"

_mode=""

while getopts "m:" opt; do
	case "${opt}" in
	m)	_mode="${OPTARG}";;
	*)	usage;;
	esac
done
shift $((OPTIND - 1))
{ [ -n "${_mode}" ] && [ $# -eq 0 ]; } || usage

setmode "${_mode}"

config_load <<'EOF'
ROBSDDIR="${robsddir}"
EOF

# shellcheck disable=SC2153
EXEC="${ROBSDEXEC:-/usr/local/libexec/robsd/robsd-exec} -m ${_MODE}"

[ -e "${ROBSDDIR}/.running" ] || fatal "${_MODE} is not running"
chflags uchg "${ROBSDDIR}/.running"
while pkill -f "^${EXEC}" 2>/dev/null; do
	sleep .1
done
