# bash completion for mgrctl (root only): options, output formats, managers from etc/mgrlist.conf after -m,
# the functions of the chosen manager (mgrctl actionlist), then common parameters (elid= plid= name= sok=ok).

# true while the word being completed is the function name (the first word that is no option or option value)
_mgrctl_completing_function() {
	local i
	for ((i = 1; i < COMP_CWORD; i++)); do
		case "${COMP_WORDS[i]}" in
			-*) continue ;;
		esac
		case "${COMP_WORDS[i - 1]}" in
			-m|--manager|-o|--format) continue ;;
		esac
		return 1
	done
	return 0
}

_mgrctl() {
	COMPREPLY=()
	[ "${EUID}" -eq 0 ] || return 0

	local mgrdir=/usr/local/sitemgr
	local cur="${COMP_WORDS[COMP_CWORD]}"
	local prev="${COMP_WORDS[COMP_CWORD - 1]}"
	local managers=core
	if [ -f ${mgrdir}/etc/mgrlist.conf ]; then
		managers=$(cut -s -d' ' -f2 ${mgrdir}/etc/mgrlist.conf)
	fi

	case "${prev}" in
		-m|--manager)
			# shellcheck disable=SC2207
			COMPREPLY=($(compgen -W "${managers}" -- "${cur}"))
			return 0
			;;
		-o|--format)
			# shellcheck disable=SC2207
			COMPREPLY=($(compgen -W "json devel html text xml" -- "${cur}"))
			return 0
			;;
	esac

	case "${cur}" in
		--*)
			# shellcheck disable=SC2207
			COMPREPLY=($(compgen -W "--manager --format --restart --lock --unlock --info --noformatted" -- "${cur}"))
			return 0
			;;
		-*)
			# shellcheck disable=SC2207
			COMPREPLY=($(compgen -W "-m -o -R -l -u -i -n" -- "${cur}"))
			return 0
			;;
	esac

	if ! _mgrctl_completing_function; then
		# shellcheck disable=SC2207
		COMPREPLY=($(compgen -W "elid= plid= name= sok=ok" -- "${cur}"))
		compopt -o nospace
		return 0
	fi

	# the manager given with -m, if it is a known one: its functions
	local i manager=""
	for ((i = 1; i < ${#COMP_WORDS[@]}; i++)); do
		if [ "${COMP_WORDS[i]}" = -m ] || [ "${COMP_WORDS[i]}" = --manager ]; then
			manager="${COMP_WORDS[i + 1]}"
			break
		fi
	done
	if [ -n "${manager}" ]; then
		if grep -qxF -- "${manager}" <<< "${managers}"; then
			local functions
			functions=$(${mgrdir}/sbin/mgrctl -m "${manager}" actionlist 2> /dev/null) || return 0
			# shellcheck disable=SC2207
			COMPREPLY=($(compgen -W "$(cut -s -d= -f2 <<< "${functions}")" -- "${cur}"))
			return 0
		fi
	fi

	[ "${COMP_CWORD}" -eq 1 ] && COMPREPLY=(-m)
	return 0
}

complete -F _mgrctl /usr/local/sitemgr/sbin/mgrctl sbin/mgrctl mgrctl
