# vim: ft=zsh noet ts=4 sts=4 sw=4

#
# confz functions for OpenRC
#

typeset -g confz_openrc_runlevel
typeset -ga confz_openrc_runlevel_deps

# find explicit dependencies of OpenRC runlevel
confz_openrc_runlevel_find_deps() {
	[[ -d /etc/runlevels/$1 ]] || die "$0: no such runlevel: ${(qqq)1}"
	confz_openrc_runlevel_deps+=( $1 )
	local d
	for d in /etc/runlevels/$1/*(N-/); do
		confz_openrc_runlevel_find_deps $d:A:t
	done
}

# get the current OpenRC runlevel
confz_openrc_get_runlevel() {
	confz_openrc_runlevel=$(</run/openrc/softlevel) || return $?
	confz_openrc_runlevel_find_deps $confz_openrc_runlevel || return $?
	# implicit dependencies
	case $confz_openrc_runlevel in
		(sysinit|shutdown)
			;;
		(boot)
			confz_openrc_runlevel_find_deps sysinit || return $?;;
		(*)
			confz_openrc_runlevel_find_deps sysinit || return $?
			confz_openrc_runlevel_find_deps boot || return $?;;
	esac
}

# check if OpenRC service is started
confz_openrc_started_check() {
	checkvars service
	do_command=( /etc/init.d/${vars[service]} start )

	/etc/init.d/${vars[service]} status -q
}

# check if all the services in current and depending runlevels are started
confz_openrc_runlevel_fully_started_check() {
	confz_openrc_get_runlevel || die "couldn't determine OpenRC runlevel"
	local runlevel service
	for runlevel in $confz_openrc_runlevel_deps; do
		for service in /etc/runlevels/$runlevel/*(N-.); do
			require openrc_started service=$service:t
		done
	done
	do_command=( true )
}