# bash completion for autoport

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

    local repos='' archs=''
    if [ -r /etc/autodist/config ]; then
        eval "$(grep -E '^AUTODIST_REPOSITORIES=|^AUTODIST_ARCHS=' /etc/autodist/config 2>/dev/null)"
        repos="${AUTODIST_REPOSITORIES[*]}"
        archs="${AUTODIST_ARCHS[*]}"
    fi

    local opts="-a -b -f -h -np -npa -nr -r -d -s -u -ud -v -x --fix --user"

    case "$prev" in
        -r|-d)
            COMPREPLY=($(compgen -W "$repos" -- "$cur"))
            return ;;
        -x)
            COMPREPLY=($(compgen -W "$archs" -- "$cur"))
            return ;;
        -u|-s|--user)
            return ;;
    esac

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

    local jobs=''
    for f in /etc/autodist/distdb /etc/autodist/distdb.d/*.db; do
        [ -r "$f" ] && jobs="$jobs $(sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)\s*=.*/\1/p' "$f" 2>/dev/null)"
    done
    COMPREPLY=($(compgen -W "$jobs" -- "$cur"))
}
complete -F _autoport autoport
