__app="nvidia-tweaker"

__commands="
    add
    remove
    list
    help
    -h
    "

__programs=$(cd /usr/share/applications && for file in *.desktop; do (basename "$file" | sed -e 's/\.desktop$//'); done)

function _get_first_command()
{
    local cmd i

    for (( i=1; i < ${#COMP_WORDS[@]}; i++ )); do
        if [[ "$1"  == *${COMP_WORDS[i]}* ]]; then
            cmd=${COMP_WORDS[i]}
            break
        fi
    done

    echo "$cmd"
}

function _commands() {

    latest="${COMP_WORDS[$COMP_CWORD]}"
    prev="${COMP_WORDS[$COMP_CWORD - 1]}"

    command="$( _get_first_command "$__commands" )"

    words=""

    case "${prev}" in
    ${__app})
      words=${__commands}
      ;;
    *)
      ;;
    esac

    if [ -z "${words}" ]; then
    case "${command}" in
    add|remove)
      words=${__programs}
      ;;
    *)
      words=""
    esac
    fi

    COMPREPLY=($(compgen -W "$words" -- $latest))
    return 0
}

complete -F _commands ${__app}
