typeset -g -a run args zsv_hooks
typeset -g -A zsv_default_handler handler zsv_hooks

if (($UID)); then
	: ${ZSVDIR:=$HOME/.zsv}
else
	: ${ZSVDIR:=/run/zsv}
fi

if ! (($+zsv_dir)); then
	zsv_dir=$ZSVDIR/foo
fi
zsv_name=$zsv_dir:t
zsv_svdir=$zsv_dir:h

zsv_hooks[run]=zsv_apply_flags

zsv_default_handler[run]=zsv_generic
zsv_default_handler[log]=zsv_logger
zsv_default_handler[cond]=check
zsv_default_flags=E

[[ -e /etc/zsvrc ]] && source /etc/zsvrc
: ${zsv_svtab:=/etc/svtab}
: ${zsv_svd:=/etc/sv.d}

# autoload all zsv_ functions
local -a func_files hook_funcs
local f
func_files=( $^fpath/zsv_*(N) )

for f in $func_files ; do
	if ! [[ -r "$f" ]]; then
		print -r >&2 - "$f is not readable"
		continue
	fi
	autoload -Uz ${f:t}
	[[ $f:t == zsv_hook_* ]] && hook_funcs+=( $f:t )
done

# run all zsv_hook_* functions (after all zsv_* functions were autoloaded)
for f in $hook_funcs; do
	$f
done

if ! (($+commands[zsv.run])); then
	# try to find zsv.run executable by emulating login shell
	for SRC in /etc/zsh/zprofile ${ZDOTDIR:-${HOME}}/.z{shenv,profile,login}; do
		[[ -e $SRC ]] && source $SRC
	done
	rehash
	if ! (($+commands[zsv.run])); then
		path+=$0:a:h
		rehash
		if ! (($+commands[zsv.run])); then
			print -r >&2 'could not find zsv.run executable'
			exit 1
		fi
	fi
fi

(($+functions[zsv_post_hooks])) && zsv_post_hooks

[[ -n $zsv_dir ]] && zsv_setdirs
# vim: ft=zsh noet ts=4 sts=4 sw=4