#!/bin/sh
# svctl: service control on s6-rc for admins and automation, see svctl(8).
# shellcheck disable=SC1091,SC2034 # libraries of svctl; variables they use
set -u
# no pathname expansion: unit names may contain glob characters
set -f

. /usr/lib/svctl/common.sh

usage() {
	. "$LIBDIR/help.sh"
	help_main >&2
	exit 2
}

VERBOSE=0
OUTPUT=text
CMD=''

# the command name, skipping the global options
_skip=0
for _a in "$@"; do
	if [ "$_skip" = 1 ]; then _skip=0; continue; fi
	case $_a in
	-o) _skip=1 ;;
	-*) ;;
	*) CMD=$_a; break ;;
	esac
done

case $CMD in
daemon-reload | apply | enable | disable | mask | unmask)
	need_root
	svctl_lock "$@"
	;;
esac

while [ $# -gt 0 ]; do
	case $1 in
	-v | --verbose) VERBOSE=1 ;;
	-o) [ $# -ge 2 ] || usage; OUTPUT=$2; shift ;;
	--output=*) OUTPUT=${1#--output=} ;;
	-h | --help) . "$LIBDIR/help.sh"; help_main; exit 0 ;;
	--) shift; break ;;
	-*) say "unknown option $1"; usage ;;
	*) break ;;
	esac
	shift
done
case $OUTPUT in
text | tsv | json) ;;
*) die 2 "unknown output format $OUTPUT (text, tsv, json)" ;;
esac
[ $# -gt 0 ] || usage
CMD=$1
shift

for _a in "$@"; do
	case $_a in
	-h | --help) . "$LIBDIR/help.sh"; help_command "$CMD"; exit $? ;;
	--) break ;;
	esac
done

case $CMD in
status | is-active | is-failed | is-enabled | failed | list-units | cat | reset-failed)
	. "$LIBDIR/status.sh" ;;
start | stop | restart | reload)
	. "$LIBDIR/control.sh" ;;
daemon-reload | apply | enable | disable | mask | unmask)
	. "$LIBDIR/reload.sh" ;;
help)
	. "$LIBDIR/help.sh"
	if [ $# -gt 0 ]; then help_command "$1"; exit $?; fi
	help_main
	exit 0 ;;
*)
	say "unknown command $CMD"
	usage ;;
esac

# command name to function name: is-active -> cmd_is_active
_f=cmd_
_r=$CMD
while :; do
	case $_r in
	*-*) _f=$_f${_r%%-*}_; _r=${_r#*-} ;;
	*) _f=$_f$_r; break ;;
	esac
done
"$_f" "$@"
