#!/bin/sh
set -e

NAME=${PWD##*/}
RUSER=
if [ "$(id -u)" -ge 1000 ] && [ -d /home/"$(id -u -n)" ] ; then
    RUSER="$(id -u -n)"
fi

[ -e /etc/runit/override-sysv.d/"$NAME".pkgrunit ] && rm /etc/runit/override-sysv.d/"$NAME".pkgrunit
if [ -d "${PWD}/cgroup" ] && [ "$(id -u)" = '0' ]; then
	/usr/sbin/runsv-cg destroy  #NOTE maybe runsv-cg remove is enough?
fi

case $1 in
(-1)
	echo "invoke-run: ERROR $1 in $NAME: runscript didn't exit normally"
	# no need to sv d service here, runsv will stop trying after the first attempt
	;;

(161)
	echo "invoke-run: WARNING for $NAME: disabled by local settings"
	sv d $NAME
	;;

(162)
	echo "invoke-run: ERROR $1 in $NAME: configtest or early setup failed"
	sv d $NAME
	;;

(170)
	echo "invoke-run: ERROR $1 in $NAME: a runtime hard dependecy is missing"
	sv d $NAME
	;;
esac

if [ -n "$RUSER" ] ; then #user services
	if [ -e /home/"$RUSER"/.runit/verbose ]; then
		echo "invoke-run: $NAME stopped"
	fi
	if [ -e /home/"$RUSER"/.runit/debug ] ; then
		echo "invoke-run: $NAME : run exit code is $1"
	fi
else
	if [ -e /etc/runit/verbose ]; then
		echo "invoke-run: $NAME stopped"
	fi
	if [ -e /etc/runit/debug ] ; then
		echo "invoke-run: $NAME : run exit code is $1"
	fi
fi
