#!/bin/sh

. /opt/etc/functions.openrc

# LOG=/opt/var/log/messages

usage() {
	echo "Usage: $(basename $0) exec-name restart-timeout kill-timeout [--- exec-args]"
	exit $1
}

[ $# -lt 3 ] && usage 1
[ $# -gt 3 -a $4 != "---" ] && usage 1

exec=$1
[ -d /tmp/run ] || mkdir /tmp/run
[ -d /tmp/run ] || exit 1
guid="$(basename ${exec})-$(uuidgen)"
pidfile=/tmp/run/${guid}.pid
[ -f ${pidfile} ] && rm ${pidfile}
timeout=$2
timetokill=$3
[ $# -gt 4 ] && exec_args=`echo $@ | sed 's/.*--- //'`

trap_break() {
	[ -f ${pidfile} ] || break
	if [ ${timetokill} -gt 0 ]; then
		start-stop-daemon --stop --exec ${exec} --retry SIGTERM/${timetokill} --pidfile ${pidfile}
	else
		start-stop-daemon --stop --exec ${exec} --pidfile ${pidfile}
	fi
	[ -f ${pidfile} ] && rm ${pidfile}
	break
}

trap trap_break HUP TERM QUIT INT KILL

while :; do
	start-stop-daemon --start --exec ${exec} --pidfile ${pidfile} --make-pidfile -- ${exec_args} &
	# Wait for signals
	wait $!
	[ -f ${pidfile} ] && rm ${pidfile}
	update_me
	echo "${ME}: daemon ${exec} exited ($?); restarting..."
	[ ${timeout} -gt 0 ] && sleep ${timeout}
done
