_thruk_cmd_options() {
    cmd=$1
    echo "help"
    thruk $cmd help 2>&1 | grep ^\ *- | awk '{print $2 }'
    return
}

_thruk_sub_commands() {
    thruk | grep ^Enabled | awk -F: '{ print $2 }' | tr -d ','
    return
}

_thruk()
{
    COMPREPLY=()


    local subcmd
    local opts=""
    local cur="${COMP_WORDS[COMP_CWORD]}"

    # simply expland files and folders if current item starts with . or /
    if [[ $cur =~ ^/|^\. ]]; then
        COMPREPLY=( $(compgen -o default -- ${cur}) )
        return 0
    fi

    # check if first arg is thruk
    if [[ ${COMP_WORDS[0]} != thruk ]]; then
        COMPREPLY=( $(compgen -o default -- ${cur}) )
        return 0
    fi

    # parse args up to COMP_CWORD
    subcmdargs=()
    local i=1
    while [ $i -lt $COMP_CWORD ]; do
        local arg=${COMP_WORDS[$i]}
        case "$arg" in
            -V)
                i=$((i + 1))
            ;;
            -*)
                :
            ;;
            *)
                if [ "x$subcmd" = "x" ]; then
                    subcmd=$arg
                else
                    subcmdargs+=($arg)
                fi
            ;;
        esac
        i=$((i + 1))
    done

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

    # thruk ...
    if [ "x$subcmd" = "x" ]; then
        opts="-V -A -b -l --list-backends --local -y --yes -f --force -v -vv -vvv "$(_thruk_sub_commands)

    # thruk plugin ...
    elif [[ $subcmd =~ plugin ]]; then
        # thruk plugin ...
        if [ ${#subcmdargs[@]} -eq 0 ]; then
            opts="$(_thruk_cmd_options $subcmd)"

        # thruk plugin disable ...
        elif [ ${subcmdargs[0]} = "disable" ]; then
            opts=$(thruk plugin list | grep ^E | awk '{print $2 }' | grep -v ^Name)

        # thruk plugin enable ...
        elif [ ${subcmdargs[0]} = "enable" ]; then
            opts=$(thruk plugin list | grep -v ^E | awk '{print $2 }' | grep -v ^Name)

        # thruk plugin remove|update ...
        elif [[ ${subcmdargs[0]} =~ remove|update ]]; then
            opts=$(thruk plugin list | awk '{print $2}' | grep -v Name)
        fi

    else
        local SUBCOMMANDS=$(_thruk_sub_commands | tr ' ' '|')
        if [[ $subcmd =~ $SUBCOMMANDS ]]; then
            opts="$(_thruk_cmd_options $subcmd)"
        fi
    fi

    if [ "x$opts" != "x" ]; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
}

complete -o default -F _thruk thruk
