# control(8) completion                                    -*- shell-script -*-
# vi: ft=sh sw=4
# SPDX-License-Identifier: GPL-2.0-or-later

_comp_control()
{
    local cur prev words cword
    _init_completion -- "$@" || return

    if [[ $cur == -* ]]; then
	COMPREPLY=($(compgen -W '--help --version' -- "$cur"))
    elif ((cword == 1)); then
	COMPREPLY=($(compgen -W "$(
	    find /etc/control.d/facilities -maxdepth 1 -type f -perm /u+x \
	    -not \( -name '.*' -o -name '*.rpm*' -o -name '*.orig' -o -name '*~' \) \
	    -printf '%f\n'
	)" -- "$cur"))
    elif ((cword == 2)); then
	[ -f "/etc/control.d/facilities/$prev" ] || return
	COMPREPLY=($(compgen -W "$(/usr/sbin/control "$prev" list)" -- "$cur"))
	COMPREPLY+=($(compgen -W 'list help status' -- "$cur"))
	if grep -qw '^new_summary' "/etc/control.d/facilities/$prev"; then
	    COMPREPLY+=($(compgen -W 'summary' -- "$cur"))
	fi
    elif ((cword == 3)) && [ $prev = help ]; then
	[ -f "/etc/control.d/facilities/${words[1]}" ] || return
	COMPREPLY=($(compgen -W "$(/usr/sbin/control "${words[1]}" list)" -- "$cur"))
    fi
} &&
    complete -F _comp_control control
