# bash completion for eos-packagelist        -*- shell-script -*-

_eos-packagelist_complete() {
    local IFS="$newline"         # handles spaces in names!
    COMPREPLY=($(compgen -W "$1" -- "$cur"))
    [[ $COMPREPLY == *= ]] && compopt -o nospace
    compopt -o nosort

    # quote the profiles but not flags
    local profile ix
    local -r count=${#COMPREPLY[@]}
    for ((ix=0; ix < count; ix++)) ; do
        profile="${COMPREPLY[$ix]}"
        case "$profile" in
            -*) ;;
            *)  [ "${profile// /}" != "$profile" ] && COMPREPLY[$ix]="'$profile'" ;;
        esac
    done
}

_eos-packagelist_() 
{
    local cur prev #words cword split
    _init_completion -s || return

    local -r newline=$'\n'

    # eos-packagelist options
    local options=(
        --help -h --list --install
    )
    # eos-packagelist profiles
    local -r profiles=$(< /etc/eos-packagelist.profiles)

    # Handle options that need sub-options.

    case "$prev" in
        *)
            # Handle all top-level parameters.
            local -r options2=$(printf "%s\n" "${options[@]}")
            case "$cur" in
                -*)
                    # Any option.
                    _eos-packagelist_complete "$options2"
                    ;;
                *)
                    # Non-option parameters.
                    _eos-packagelist_complete "$options2$newline$profiles"
                    ;;
            esac
            ;;
    esac
} &&
complete -F _eos-packagelist_ eos-packagelist
