#compdef rsm

_rsm_all_services() {
	local IFS=$'\n'
	# Extract names and email addresses from gpg --list-keys
	_values 'Active services' $(ls -1 "$SVDIR")
}

_rsm_active_services() {
	local IFS=$'\n'
	# Extract names and email addresses from gpg --list-keys
	_values 'Active services' $(ls -1 "$RUNSVDIR")
}

_rsm_common_args() {
	_arguments : \
		'-c[Enable/disable color output, defaults to auto]:Enable color:(yes no auto)' \
		'-d[Directory to look into, defaults to env SVDIR or /run/runit/service is unset]:directory:_files -/' \
		'-h[Print this message and exit]' \
		"-l[Show log processes, this is a shortcut for 'status -l']" \
		"-t[Tree view, this is a shortcut for 'status -t']" \
		"-u[User mode, this is a shortcut for '-d ~/runit/service']" \
		'-v[Increase verbosity]' \
		'-V[Print the version number and exit]'
}

_rsm_subcommands() {
	local subcommands=(
		'status:Default subcommand, show process status'
		'enable:Enable the service(s) (remove the "down" file, does not start service'
		'disable:Disable the service(s) (create the "down" file, does not stop service'
		'start:Start the service'
		'stop:Stop the service'
		'restart:Restart the service'
		'reload:Reload the service (send SIGHUP)'
		"logs:Outputs the service's logfilenames and their access & error logs from /var/log/<serice>/"
		'alllogs:The same like logs <service>'
		"errorlogs:Outputs the service's logfilenames and their errorlogs from /var/log/<service>/"
	)
	_describe -t commands 'rsm' subcommands
}

_rsm() {
	local -a args subcommands cmd havesubcmd tmpwords lastcmd SVDIR RUNSVDIR
	# NOTE Change there variables to your configuration
	SVDIR='/etc/runit/sv'
	RUNSVDIR='/etc/runit/runsvdir/default'
	havesubcmd=NONE
	tmpwords=("${words[@]}")

	while true
	do
		cmd="${tmpwords[2]}"
		case "$cmd" in
			-h|-V)
				# Help and version options override everything else
				return
				;;
			-c)
				havesubcmd=OPTARG
				shift tmpwords
				;;
			-d)
				havesubcmd=OPTARG
				shift tmpwords
				;;
			-*)
				havesubcmd=OPT
				shift tmpwords
				;;
			"")
				break
				;;
			*)
				if [ "$havesubcmd" = OPTARG ]
				then
					if [ "$lastcmd" = "-d" ]
					then
						SVDIR="$cmd"
					fi
					havesubcmd=OPT
					shift tmpwords
				else
					havesubcmd=SUBCMD
					break
				fi
				;;
		esac
		lastcmd="$cmd"
	done

	if [ "$havesubcmd" = SUBCMD ]
	then
		words=("${tmpwords[@]}")

		cmd="${words[2]}"
		# CURRENT=$((CURRENT - 1))
		shift words
		case "$cmd" in
			status)
				_rsm_active_services
				_arguments : \
					'-t[Enables tree mode (process tree)]' \
					'-l[Enables log mode (show log processes)]'
				;;
			enable|logs|alllogs|errorlogs)
				_rsm_all_services
				;;
			disable|start|stop|restart|reload)
				_rsm_active_services
				;;
			*)
				_rsm_subcommands
				;;
		esac
	else
		if [ "$havesubcmd" = NONE ] || [ "$havesubcmd" = OPT ]
		then
			_rsm_subcommands
			_rsm_common_args
		elif [ "$havesubcmd" = OPTARG ]
		then
			_rsm_common_args
		fi
	fi
	return 0
}

_rsm
