_aur_completion()
{
    local cur prev words cword
    _get_comp_words_by_ref cur prev words cword

    declare -A default_cmds

    default_cmds[build]=''
    default_cmds[chroot]=''
    default_cmds[fetch]=''
    default_cmds[pkglist]=''
    default_cmds[repo]=''
    default_cmds[repo-filter]=''
    default_cmds[srcver]=''
    default_cmds[sync]='--auto-key-retrieve --bind-rw: --bind: --chroot --clean --cleanbuild --columns --continue --database: --directory: --exclude: --ff --force --format: --ignore-arch --ignore-file: --ignore: --keep-going: --log --makepkg-args: --makepkg-conf: --new --no-build --no-check --no-confirm --no-graph --no-provides --no-sync --no-ver --no-ver-argv --no-view --pacman-conf: --pkgver --prefix --prevent-downgrade --provides-from: --rebase --rebuild --rebuild-all --rebuild-tree --remove --reset --rmdeps --root: --save: --sign --temp --upgrades --user: --verify -A -C -D: -K -L -R -S -T -U: -c -d: -f -k: -n -o -r -u -v'
    default_cmds[vercmp]=''
    default_cmds[view]=''
    default_cmds[graph]=''
    default_cmds[format]=''
    default_cmds[repo-parse]=''
    default_cmds[query]=''
    default_cmds[depends]=''
    default_cmds[search]=''

    # complete subcommands
    if [[ $cword -eq 1 ]]; then
        COMPREPLY=( $(compgen -W "${!default_cmds[*]}" -- "$cur") )
        return
    fi

    # If there's an override for subcommand, use it
    if declare -F "_aurutils_${words[1]/-/_/}" >/dev/null ; then
        "_aurutils_${words[1]}"
        return
    fi

    # Complete with the generated opts stored above, unless the previous option
    # is stored with an : suffix, because the option requires an argument.
    # Fallback to default (files) completion in such cases.

    _fallback_completion
}

_fallback_completion(){
    opts=(${default_cmds[${words[1]}]})
    if [[ ${opts[*]} != *$prev:* ]] || [[ $cword -eq 2 ]]; then
        COMPREPLY=($(compgen -W "${opts[*]%:}" -- "$cur"));
    fi
}

_complete_with_repos() {
    opts=($(aur repo --repo-list))
    COMPREPLY=($(compgen -W "${opts[*]}" -- "$cur"))
}

_aurutils_build() {
    case $prev in
        -d|--database|--repo)
            _complete_with_repos ;;
        *) _fallback_completion ;;
    esac
}

_aurutils_repo() {
    case $prev in
        -d|--database|--repo)
            _complete_with_repos ;;
        *) _fallback_completion ;;
    esac
}

_aurutils_repo_filter() {
    case $prev in
        -d|--database|--repo)
            _complete_with_repos ;;
        *) _fallback_completion ;;
    esac
}

_aurutils_sync() {
    case $prev in
        -d|--database|--repo)
            _complete_with_repos ;;
        *) _fallback_completion ;;
    esac
}

complete -o bashdefault -o default -o nosort -F _aur_completion aur
