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

#
# confz functions for zsv
#

zmodload zsh/datetime

confz_zsv_configured_check() {
	local -a confs failures
	local f

	confs=( /etc/sv.d/*(N-.) )
	[[ -e /etc/svtab ]] && confs+=( /etc/svtab )
	(($#confs)) || die "no zsv configuration found"
	for f in $confs; do
		[[ $vars[svdir]/.zsv -nt $f ]] || failures+=(
			"$vars[svdir]/.zsv not newer than ${(qqq)f}"
		)
	done

	do_command=( zsvgen )
	fail_reason=${(j:,:)failures}
	return $#failures
}


confz_runsv_running_check() {
	checkvars service

	#require zsv_configured

	[[ -e $vars[service] ]] || die
	do_command=( sv start $vars[service] )

	local START
	START=$EPOCHREALTIME
	# wait up to 10s for supervise/control to appear
	while (( $EPOCHREALTIME - $START < 10 )); do
		[[ -e $vars[service]/supervise/control ]] && break
		if (($+commands[inotifywait])); then
			inotifywait -r -q -t 1 -e create,move,close_write $vars[service]
		else
			sleep 0.2
		fi
	done
	sv check $vars[service]
}


confz_zsv_autorestart_check() {
	checkvars service

	require runsv_running :service

	do_command=( sv restart $vars[service] )

	local -a failures
	local f
	for f in ${(f)"$(<$vars[service]/restart.files)"}; do
		[[ -e $f ]] || failures+=( "${(qqq)f} does not exist" )
		[[ $vars[service]/restart.files -nt $f ]] || failures+=(
			"${(qqq)f} is newer than restart.files"
		)
	done

	fail_reason=${(j:,:)failures}
	return $#failures
}


confz_zsv_autoreload_check() {
	checkvars service

	require zsv_autorestart :service

	do_command=( sv hup $vars[service] )

	local -a failures
	local f
	for f in ${(f)"$(<$vars[service]/reload.files)"}; do
		[[ -e $f ]] || failures+=( "${(qqq)f} does not exist" )
		[[ $vars[service]/reload.files -nt $f ]] || failures+=(
			"${(qqq)f} is newer than reload.files"
		)
	done

	fail_reason=${(j:,:)failures}
	return $#failures
}


confz_zsv_autoreload_current_check() {
	defvar svdir /run/service

	require zsv_configured :svdir

	local sv
	for sv in $vars[svdir]/*(-/); do
		if ! [[ -e $sv/down ]]; then
			if [[ -e $sv/reload.files ]]; then
				require zsv_autoreload service=$sv
			elif [[ -e $sv/restart.files ]]; then
				require zsv_autorestart service=$sv
			fi
		fi
	done
}