# this is sourced at the beginning of any initscript

# /etc/runit/lsb.runit.forward = forward action to sv if /etc/sv/<service> exists and is enabled;
#                                                noop if <service> is disabled; continue with sysv script
#                                                if /etc/sv/<service> does not exists # implicit default
# /etc/runit/lsb.runit.mask = noop if /etc/sv/<service> exists
# /etc/runit/lsb.runit.sysv = always continue with sysv regardless any /etc/sv/<service>

if [ -e /run/runit.stopit ] || pidof runsvdir > /dev/null ; then
# runit init or a running runsvdir (likely runit-run)
 if [ ! -e /etc/runit/lsb.runit.sysv ]; then
 #get the service basename and action, like 40-systemd
    if [ -n "${__init_d_script_name:-}" ]; then
        service="$__init_d_script_name"
        action="$1"
        [ x"${2:-}" = 'x--force-sysv' ] && forcesysv=1
    elif [ "${0##*/}" = "init-d-script" ] || [ "${0##*/}" = "${1:-}" ]; then
        service="$1"
        action="$2"
	[ x"${3:-}" = 'x--force-sysv' ] && forcesysv=1
    else
        service="$0"
        action="${1:-}"
        [ x"${2:-}" = 'x--force-sysv' ] && forcesysv=1
    fi
    service=${service##*/}
    service="${service%.sh}"
    if [ ! -e /etc/runit/lsb.runit.mask ]; then # forward
        if [ -d "/etc/sv/$service" ] && [ -h "/etc/service/$service" ]; then
            if  [ -z "${forcesysv:-}" ]; then
                [ -e "/usr/share/runit/meta/$service/installed" ] && exit 0 #dh-runit managed
                [ -e "/etc/sv/$service/.meta/bin" ] && exit 0 # runit trigger-sv
            fi
            case "$action" in
              start|stop|restart|reload|status|try-restart|force-stop|force-reload|force-restart)
              if [ -z "${forcesysv:-}" ]; then
                sv "$action" "$service" || true
                exit 0
              fi
              ;;
              *)
                echo "WARNING: $action not supported by sv, giving up"
                exit 0
              ;;
            esac
        else
	    [ -d "/etc/sv/$service" ] && exit 0 # disabled
        fi
    else # mask
        [ -d "/etc/sv/$service" ] && exit 0
    fi
 fi
fi
