# Bash completion for the offline-installer CLI tool
#
# This script gives the offline-installer CLI the ability to use <Tab> completion:
#
# The bash-completion package loads this script lazily on the first <Tab>
# press whenever `offline-installer` is found in $PATH and the script lives
# in /usr/share/bash-completion/completions/offline-installer.
#

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

    local commands="get install"
    local i command=""
    for (( i = 1; i < cword; i++ )); do
        if [[ " $commands " == *" ${words[i]} "* ]]; then
            command=${words[i]}
            break
        fi
    done

    # No subcommand selected (yet): complete the subcommand names.
    if [[ -z $command ]]; then
        COMPREPLY=( $( compgen -W "$commands -h --help" -- "$cur" ) )
        return 0
    fi

    case $command in
        get)
            case $prev in
                --depth)
                    # --depth expects an integer; nothing useful to complete.
                    return 0
                    ;;
            esac
            if [[ $cur == -* ]]; then
                COMPREPLY=( $( compgen -W '--depth -h --help' -- "$cur" ) )
            else
                # Same mechanism as apt's completion uses for package names.
                COMPREPLY=( $( apt-cache --no-generate pkgnames "$cur" 2> /dev/null ) )
            fi
            ;;
        install)
            if [[ $cur == -* ]]; then
                COMPREPLY=( $( compgen -W '--dry-run -y --yes -h --help' -- "$cur" ) )
            else
                # The argument is a .tar.gz archive OR a folder of .deb files;
                # _filedir completes matching files and directories.
                _filedir '@(tar.gz|deb)'
            fi
            ;;
    esac

    return 0
}

complete -F _offline_installer offline-installer
