# bash completion for check_nvidia_smi                       -*- shell-script -*-

_check_nvidia_smi()
{
    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=()

    local modes='temperature power clocks memory utilization fan pcie ecc all'
    # 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 $modes" -- "$cur")
        return
    fi

    case $prev in
        --nvidia-smi)
            compopt -o filenames 2>/dev/null
            mapfile -t COMPREPLY < <(compgen -f -- "$cur")
            return
            ;;
        --warning-reasons | --critical-reasons)
            # comma separated list: offer the reasons for the item being typed
            local head=${cur%,*} item=${cur##*,} reason
            [[ $head == "$cur" ]] && head= || head+=,
            for reason in none gpu_idle applications_clocks_setting sw_power_cap hw_slowdown sync_boost \
                sw_thermal_slowdown hw_thermal_slowdown hw_power_brake_slowdown display_clock_setting; do
                [[ $reason == "$item"* ]] && COMPREPLY+=("$head$reason")
            done
            return
            ;;
        -i | --index | -t | --timeout | --*-warning | --*-critical | --busy)
            return
            ;;
    esac

    local options='-h --help -i --index -t --timeout --nvidia-smi'
    case $mode in
        temperature) options+=' --temperature-warning --temperature-critical --tlimit-warning --tlimit-critical' ;;
        power) options+=' --power-warning --power-critical' ;;
        clocks) options+=' --warning-reasons --critical-reasons' ;;
        memory) options+=' --memory-warning --memory-critical' ;;
        utilization) options+=' --utilization-warning --utilization-critical' ;;
        fan) options+=' --fan-warning --fan-critical' ;;
        pcie) options+=' --ignore-width --check-gen --busy' ;;
        ecc) options+=' --ecc-warning --ecc-critical --require-ecc' ;;
        all) options+=' --temperature-warning --temperature-critical --tlimit-warning --tlimit-critical
            --power-warning --power-critical --warning-reasons --critical-reasons --memory-warning
            --memory-critical --utilization-warning --utilization-critical --fan-warning --fan-critical
            --ignore-width --check-gen --busy --ecc-warning --ecc-critical --require-ecc' ;;
    esac
    mapfile -t COMPREPLY < <(compgen -W "$options" -- "$cur")
}
complete -F _check_nvidia_smi check_nvidia_smi
