# bash completion for rpi-power-hat

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

    # Known values
    local ports=(B1 B2 T1 T2)
    local models=(5 4 0)

    # Base subcommands (fallback)
    local subs=(
        get set mass-storage flash-image log-current log-power ssh
        get-hostname set-hostname
        help list ls
    )

    # Try to augment with dynamic list from the tool if available
    if command -v rpi-power-hat >/dev/null 2>&1; then
        # Expect just names per line; take first field defensively
        local dyn
        dyn=$(rpi-power-hat list 2>/dev/null | awk 'NF>0 && $1!="Available" {print $1}')
        if [ -n "$dyn" ]; then
            # shellcheck disable=SC2206
            subs=(${subs[@]} $dyn)
        fi
    fi

    # Completing the subcommand
    if [ $COMP_CWORD -le 1 ]; then
        COMPREPLY=( $(compgen -W "${subs[*]}" -- "$cur") )
        return 0
    fi

    case "$cmd" in
        get)
            if [ $COMP_CWORD -eq 2 ]; then
                COMPREPLY=( $(compgen -W "${ports[*]} all" -- "$cur") )
            fi
            ;;
        set)
            if [ $COMP_CWORD -eq 2 ]; then
                COMPREPLY=( $(compgen -W "${ports[*]} all" -- "$cur") )
            elif [ $COMP_CWORD -eq 3 ]; then
                COMPREPLY=( $(compgen -W "1 0" -- "$cur") )
            fi
            ;;
        mass-storage)
            if [ $COMP_CWORD -eq 2 ]; then
                COMPREPLY=( $(compgen -W "${ports[*]}" -- "$cur") )
            elif [ $COMP_CWORD -eq 3 ]; then
                COMPREPLY=( $(compgen -W "${models[*]}" -- "$cur") )
            fi
            ;;
        flash-image)
            if [ $COMP_CWORD -eq 2 ]; then
                COMPREPLY=( $(compgen -W "${ports[*]}" -- "$cur") )
            elif [ $COMP_CWORD -eq 3 ]; then
                COMPREPLY=( $(compgen -W "latest nightly" -- "$cur") )
            fi
            ;;
        log-current|log-power)
            if [ $COMP_CWORD -eq 2 ]; then
                COMPREPLY=( $(compgen -W "${ports[*]}" -- "$cur") )
            else
                COMPREPLY=( $(compgen -W "-s --save" -- "$cur") )
            fi
            ;;
        ssh)
            if [ $COMP_CWORD -eq 2 ]; then
                COMPREPLY=( $(compgen -W "${ports[*]}" -- "$cur") )
            fi
            ;;
        get-hostname)
            if [ $COMP_CWORD -eq 2 ]; then
                COMPREPLY=( $(compgen -W "${ports[*]}" -- "$cur") )
            elif [ $COMP_CWORD -eq 3 ]; then
                COMPREPLY=( $(compgen -W "-h --history" -- "$cur") )
            fi
            ;;
        set-hostname)
            if [ $COMP_CWORD -eq 2 ]; then
                COMPREPLY=( $(compgen -W "${ports[*]}" -- "$cur") )
            fi
            ;;
        *)
            ;;
    esac
}

complete -F _rpi_power_hat rpi-power-hat

