#!/bin/sh -eu
#Copyright: Debian runit maintainers
#           2026 Aitor <aitor@genuen.org>
#License: BSD-3-clause

usage () {
	cat << EOF >&2
Program /lib/runit/invoke-run must only be used as interpreter for
run scripts with full path.

Please, refer to documentation in manual page invoke-run(5). If error
persist, file bug report aganist 'runit' Debian package.
EOF
}

if [ $# = 0 ] ; then
	usage
	exit 1
fi

if [ ! -x "${PWD}"/run ]; then
	echo "invoke-run: error: ${PWD}/run does not exists or not executable"
	usage
	exit 1
fi

# Stock check: .meta/installed in /etc/sv but the shipping package was
# removed. On genuens services live in /etc/sv (not /usr/share/runit/sv),
# so only down the service if the daemon binary is also gone.
if [ -f "/etc/sv/${PWD##*/}/.meta/installed" ] ; then
	if ! [ -f "/usr/share/runit/meta/${PWD##*/}/installed" ] ; then
		if ! [ -d "/usr/share/runit/sv/${PWD##*/}" ]; then
			bin=
			[ -r "${PWD}/.meta/bin" ] && bin=$(cat "${PWD}/.meta/bin")
			if [ -z "$bin" ] || [ ! -e "$bin" ]; then
				echo "invoke-run: ${PWD##*/} binary not installed"
				sv down "${PWD##*/}"
				exit 0
			fi
		fi
	fi
fi

if [ -r "${PWD}/.meta/bin" ] ; then
	if [ ! -e "$(cat ${PWD}/.meta/bin)" ]; then
		echo "invoke-run: ${PWD##*/} binary not installed"
		sv down "${PWD##*/}"
	else
		stat -c %W "$(cat ${PWD}/.meta/bin)" > "${PWD}/.meta/wtime"
	fi
fi

if [ -r "/etc/default/${PWD##*/}" ] ; then
	set -a +u
	. "/etc/default/${PWD##*/}"
	set +a -u
fi

# Native runit boot: /etc/init.d/* are OpenRC scripts. "stop --force-sysv"
# fails, and with set -e that aborted every invoke-run service.
if [ ! -f /etc/runit/native.boot.run ] && [ -x "/etc/init.d/${PWD##*/}" ] ; then
	# Stopping some services (e.g display manager) is disruptive
	# and must be done only manually by user.
	if [ -f "/usr/share/runit/meta/${PWD##*/}/noreplace" ] || \
	    [ -f "${PWD}/.meta/noreplace" ] ; then
		if "/etc/init.d/${PWD##*/}" status --force-sysv >/dev/null 2>&1 ; then
			sv down "${PWD##*/}"
			exit 0
		fi
	fi
	if [ ! -h "/etc/init.d/${PWD##*/}" ] && [ ! -h /sbin/start-stop-daemon ]; then
		"/etc/init.d/${PWD##*/}" stop --force-sysv >/dev/null || true
	fi
fi

XCHPST=""
if [ -x /usr/bin/xchpst ]; then
    if [ -r "${PWD}/xchopts" ] ; then
       export XCHPST="xchpst --file ${PWD}/xchopts"
    fi
fi

if [ -e /etc/runit/verbose ]; then
        echo "invoke-run: starting ${PWD##*/}"
fi

# Native boot: oneshots are not in /etc/service. Prefer the stage1 helper so
# "sv once <oneshot>" from daemons works.
if [ -f /etc/runit/native.boot.run ]; then
	if [ -x /usr/lib/runit/stage1/sv ]; then
		PATH=/usr/lib/runit/stage1:$PATH
		export PATH
	elif [ -x /usr/lib/runit-services/stage1/sv ]; then
		PATH=/usr/lib/runit-services/stage1:$PATH
		export PATH
	fi
fi

if [ -d "${PWD}/env" ] ; then
	exec chpst -e "${PWD}/env" -- /bin/sh "${PWD}"/run
else
	exec /bin/sh "${PWD}"/run
fi
