# bash completion for dnf5

_do_dnf5_completion()
{
    local cur prev words cword comp_args

    # Test if bash-completion supports "_comp_initialize" (added in bash-completion 2.12)
    type _comp_initialize >/dev/null 2>&1
    if [[ $? -eq 0 ]]; then
        _comp_initialize -n "><=;|&(:" -- "$@" || return
    else
        # legacy function call (deprecated since bash-completion 2.12)
        _init_completion -n "><=;|&(:" -- "$@" || return
    fi

    case ${COMP_TYPE} in
        # <TAB> (code 9) - normal completion, the identical part of the suggestions is completed
        # '%' (code 37) - menu completion, cyclically completes the suggestions from the list
        # In these cases the list of suggestions is not printed and we do not want
        # to complete the argument with a description (help).
        9 | 37)
            mapfile -t COMPREPLY <<<$("${1}" "--complete=${cword},add_description=0" "${words[@]}")
            ;;
        *)
            mapfile -t COMPREPLY <<<$("${1}" "--complete=${cword}" "${words[@]}")
            ;;
    esac

    # In Bash, with a colon in COMP_WORDBREAKS, words containing colons are
    # always completed as entire words if the word to complete contains a colon.
    # This behavior is fixed by removing the colon-containing prefix from the items in COMPREPLY.
    # A side effect is the removal of this prefix in the list of bash completion suggestions.
    #
    # The preferred solution is to remove the colon ':' from COMP_WORDBREAKS in .bashrc:
    #    COMP_WORDBREAKS=${COMP_WORDBREAKS//:}
    if [[ ${cur} == *:* && ${COMP_WORDBREAKS} == *:* ]]; then
        # Remove colon-word prefix from items in COMPREPLY
        local _colon_word=${cur%"${cur##*:}"}
        COMPREPLY=("${COMPREPLY[@]#"$_colon_word"}")
    fi
}

_complete_dnf5_cmds="dnf5"
if [ "$(readlink -fn /usr/bin/dnf)" = "/usr/bin/dnf5" ]; then
    _complete_dnf5_cmds+=" dnf"
fi

complete -F _do_dnf5_completion -o nosort -o nospace $_complete_dnf5_cmds
