# bash completion for check_part-db                          -*- shell-script -*-

_check_part_db()
{
    local cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]}
    # --option=value: bash splits at the =
    if [[ $cur == = ]]; then
        cur=
    elif [[ $prev == = && $COMP_CWORD -ge 2 ]]; then
        prev=${COMP_WORDS[COMP_CWORD-2]}
    fi
    COMPREPLY=()

    # the mode is the first word that is no option, before it come only -h and -V
    local i mode=
    for ((i = 1; i < COMP_CWORD; i++)); do
        if [[ ${COMP_WORDS[i]} != -* ]]; then
            mode=${COMP_WORDS[i]}
            break
        fi
    done
    if [[ -z $mode ]]; then
        mapfile -t COMPREPLY < <(compgen -W '-h --help -V --version
            health web stats stock token' -- "$cur")
        return
    fi

    case $prev in
        -H | --hostname)
            mapfile -t COMPREPLY < <(compgen -A hostname -- "$cur")
            return
            ;;
        -f | --token-file | --ca-cert)
            compopt -o filenames 2>/dev/null
            mapfile -t COMPREPLY < <(compgen -f -- "$cur")
            return
            ;;
        -e | --entity)
            # the collections the stats help names; --list shows all of an instance
            mapfile -t COMPREPLY < <(compgen -W 'parts categories footprints manufacturers
                suppliers storage_locations part_lots projects attachments' -- "$cur")
            return
            ;;
        -p | --port | -u | --uri | -t | --timeout | -T | --token | -w | --warning | \
            -c | --critical | --probe-path | --expect-string | --cert-warning | \
            --cert-critical | --threshold | --workers | --zero-warning | --zero-critical | \
            --page-size | --max-pages | --max-list)
            return
            ;;
    esac

    local options='-h --help -H --hostname -p --port -S --ssl --no-ssl -u --uri
        -t --timeout --insecure --ca-cert'
    [[ $mode != web ]] && options+=' -T --token -f --token-file'
    case $mode in
        health) options+=' -w --warning -c --critical --probe-path' ;;
        web) options+=' -w --warning -c --critical --expect-string --cert-warning
            --cert-critical --no-cert-check' ;;
        stats) options+=' -e --entity --threshold --list --strict --workers' ;;
        stock) options+=' -w --warning -c --critical --full-scan --zero-warning
            --zero-critical --page-size --max-pages --max-list' ;;
        token) options+=' -w --warning -c --critical' ;;
    esac
    mapfile -t COMPREPLY < <(compgen -W "$options" -- "$cur")
}
complete -F _check_part_db check_part-db
