#!/bin/bash completion for cinder-manage

_cinder-manage(){
    local cur prev
    local -A ARGS MAP FORCE OPTS OPTS_SUB MULTI

    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    OPTS=([config-dir]='--config-dir' [config-file]='--config-file' [state_path]='--state_path' [use-json]='--use-json' [syslog-log-facility]='--syslog-log-facility' [use-journal]='--use-journal' [use-syslog]='--use-syslog' [watch-log-file]='--watch-log-file' [log-dir]='--log-dir' [log-file]='--log-file' [log-date-format]='--log-date-format' [log-config-append]='--log-config-append' [debug]='--debug -d' [shell_completion]='--shell_completion' [help]='--help -h' [backup]='backup' [cg]='cg' [cluster]='cluster' [config]='config' [db]='db' [host]='host' [quota]='quota' [service]='service' [util]='util' [version]='version' [volume]='volume')
    OPTS_SUB=([backup]='help="-h --help"' [cg]='help="-h --help"' [cluster]='help="-h --help"' [config]='help="-h --help"' [db]='help="-h --help"' [host]='help="-h --help"' [quota]='help="-h --help"' [service]='help="-h --help"' [util]='help="-h --help"' [version]='help="-h --help"' [volume]='help="-h --help"' )
    ARGS=([config-dir]=' ' [config-file]=' ' [state_path]=' ' [use-json]=' ' [syslog-log-facility]=' ' [use-journal]=' ' [use-syslog]=' ' [watch-log-file]=' ' [log-dir]=' ' [log-file]=' ' [log-date-format]=' ' [log-config-append]=' ' [debug]=' ' [shell_completion]='bash zsh')
    MAP=([--config-dir]=config-dir [--config-file]=config-file [--state_path]=state_path [--use-json]=use-json [--syslog-log-facility]=syslog-log-facility [--use-journal]=use-journal [--use-syslog]=use-syslog [--watch-log-file]=watch-log-file [--log-dir]=log-dir [--log-file]=log-file [--log-date-format]=log-date-format [--log-config-append]=log-config-append [--debug]=debug [-d]=debug [--shell_completion]=shell_completion [-h]=help [--help]=help)
    MULTI=()

    if [ ! -z "$prev" ]; then
        # if is an argument complete with list of choice if define
        prev_key=${MAP[$prev]}
        if [ ! -z $prev_key ] && [ ! -z "${ARGS[$prev_key]}" ]; then
            COMPREPLY=($(compgen -W "${ARGS[$prev_key]}" -- "${cur}"))
            return 0
        fi
    fi
    for in_use in ${COMP_WORDS[@]:1}; do
        key=${MAP[$in_use]}
        IFS='|'
        if [[ -v OPTS_SUB[$key] ]];then
        # If is a subcommand redefine completion
            unset OPTS
            local -A OPTS
            for el in ${OPTS_SUB[$key]}; do
                IFS='='
                read k v <<< ${el}
                IFS='|'
                OPTS+=( [${k}]="${v}" )
            done
        fi
        unset IFS
        # Unset option that is already use
        if [[ -z "MULTI[$key]" ]]; then
            unset OPTS[$key]
            unset ARGS[$key]
        fi
    done
    compl="${OPTS[@]}"
    COMPREPLY=($(compgen -W "${compl}" -- "${cur}"))
    return 0
}

complete -F _cinder-manage cinder-manage

