# mosquitto-plugin-iqrf-manager(1) completion                                      -*- shell-script -*-

_mosquitto-plugin-iqrf-manager() {
    local curr prev opts
    curr="${COMP_WORDS[COMP_CWORD]}"

    # available commands
    local commands="
        help
        version
        list
        get
        create
        block
    "
    # command options
    local shared_opts="-h --help -d --db"
    local list_opts="$shared_opts"
    local get_opts="$shared_opts -i --id -j --json"
    local create_opts="$shared_opts -u --username -p --password -j --json"
    local block_opts="$shared_opts -i --id"

    # no command specified yet
    if [[ $COMP_CWORD == 1 ]]; then
        COMPREPLY=( $(compgen -W "$commands" -- "$curr") )
        return 0
    fi

    # command received
    cmd="${COMP_WORDS[1]}"
    curr="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    # help found, stop completing
    for token in "${COMP_WORDS[@]}"; do
        case "$token" in
            -h|--help)
                COMPREPLY=()
                return
                ;;
        esac
    done

    # if specifying database file, look for db files
    case "$prev" in
        -d|--db)
            local files=( $(compgen -f -- "$curr") )
            COMPREPLY=()

            for file in "${files[@]}"; do
                if [[ -d "$file" ]]; then
                    compopt -o nospace 2>/dev/null
                    COMPREPLY+=( "$file/" )
                    continue
                fi

                if [[ "$file" == *.db ]]; then
                    COMPREPLY+=( "$file" )
                fi
            done
            return 0
            ;;
    esac

    case "$cmd" in
        help|version)
            COMPREPLY=()
            return
            ;;
        list)
            COMPREPLY=( $(compgen -W "$list_opts" -- "$curr"))
            return
            ;;
        get)
            COMPREPLY=( $(compgen -W "$get_opts" -- "$curr"))
            return
            ;;
        create)
            COMPREPLY=( $(compgen -W "$create_opts" -- "$curr"))
            return
            ;;
        block)
            COMPREPLY=( $(compgen -W "$block_opts" -- "$curr"))
            return
            ;;
    esac
}

complete -F _mosquitto-plugin-iqrf-manager mosquitto-plugin-iqrf-manager

# ex: filetype=sh
