#!/bin/bash
# $1 name
_acbs_comp_package() {
    local tree
    tree="$(acbs-build -q 'tree:default' 2>/dev/null)"
    if [[ -z "$tree" || ! -d "$tree" ]]; then
        return
    fi
    local PGROUPS="$(find "$tree/groups/" -maxdepth 1 -mindepth 1 -type f -printf 'groups/%f\n')"
    COMPREPLY=($(compgen -W "$PGROUPS" -- "${1}"))
    if [[ "$1" == *'/'* ]]; then
        return
    fi
    COMPREPLY+=($(find "$tree" -maxdepth 2 -mindepth 2 -type d -not -path "$tree/.git" -name "${1}*" -printf '%f\n'))
}

_acbs()
{
    local cur prev words cword
    _init_completion || return

    if [[ $cur == -* ]]; then
        COMPREPLY=($(compgen -W '-v --version -d --debug -t --tree -q --query -c --clear -k --skip-deps -g --get -r --resume -w --write -e --reorder -p --print-tasks' -- "$cur"))
    elif [[ $prev == "-t" || $prev == "--tree" ]]; then
        forest="$(acbs-build -q 'path:conf' 2>/dev/null)/forest.conf"
        if [[ "$?" -ne "0" ]]; then
            return
        fi
        COMPREPLY=($(gawk 'match($0,/\[(.*)\]/,m) {print m[1]}' "$forest"))
    elif [[ $prev == "-r" || $prev == "--resume" ]]; then
        COMPREPLY=($(compgen -f -- "$cur"))
    else
        _acbs_comp_package "$cur"
    fi
}

complete -F _acbs acbs-build
