# Bash completion for t2build

_t2build() {
    local cur prev words cword

    if type -t _init_completion &> /dev/null; then
        _init_completion -n = || return
    else
        COMPREPLY=()
        cur="${COMP_WORDS[COMP_CWORD]}"
        prev="${COMP_WORDS[COMP_CWORD-1]}"
    fi

    local args=(
        -a --all -b --build -i --install -R --rebuild -I --ignore -f --force
        -r --configure -d --debug -c --clean -u --unload -O -p --plugin-dir
        -l --list -P --profile -D --doc -e --empty -y --yes -1 -U --update
        -k --package -kJ --package-xz -kj --package-bz2 -kt --package-tar
        -kz --package-gz -K --package-all -KJ --package-all-xz -B --backend -G
        -Kj --package-all-bz2 -Kt --package-all-tar --Kz --package-all-gz
        -X --bypass-lock --iwyu -\? -h --help
    )

    case "$prev" in
        -p|--plugin-dir)
            if type -t _filedir &> /dev/null; then
                _filedir -d
            else
                compopt -o dirnames 2> /dev/null
                COMPREPLY=($(compgen -d -- "$cur"))
            fi
            return
            ;;
        -I|--ignore)
            if type -t _filedir &> /dev/null; then
                _filedir
            else
                compopt -o filenames 2> /dev/null
                COMPREPLY=($(compgen -f -- "$cur"))
            fi
            return
            ;;
        -B|--backend)
            local backends=(cmake meson autotools autotools-out-of-tree)
            COMPREPLY=($(compgen -W "${backends[*]}" -- "$cur"))
            return
            ;;
        -G)
            if type cmake &> /dev/null; then
                local IFS=$'\n'
                local quoted
                printf -v quoted %q "$cur"
                COMPREPLY=($(compgen -W '$(cmake --help 2> /dev/null | sed -n \
                    -e "1,/^Generators/d" \
                    -e "/^  *[^ =]/{s|^ *\([^=]*[^ =]\).*$|\1|;s|^|\"|g;s|$|\"|g;p}" \
                    2> /dev/null)' -- "$quoted"))
            fi
            return
            ;;
        -O)
            local opts=(0 g 1 2 3 s)
            COMPREPLY=($(compgen -W "${opts[*]}" -- "$cur"))
            return
            ;;
    esac

    if [[ "$cur" == -* ]]; then
        COMPREPLY=($(compgen -W "${args[*]}" -- "$cur"))
        return
    fi

    local plugins=(tranalyzer2 t2b2t t2whois fextractor)
    for i in "$T2PLHOME/"*; do
        local b=$(basename "$i")
        if [ -d "$i" ] && [ "$b" != "t2PSkel" ]; then
            plugins+=($b)
        fi
    done

    if [ "$prev" = "-b" ]; then
        if type compopt &> /dev/null; then
            compopt -o nospace
        fi
        COMPREPLY=($(compgen -f -W "${plugins[*]}" -- "$cur"))
    else
        COMPREPLY=($(compgen -W "${plugins[*]}" -- "$cur"))
    fi
}

complete -F _t2build t2build
