# fastboot completion                                           -*- shell-script -*-
# © 2023 Andreas Itzchak Rehberg (izzysoft ät qumran dot org)

_fastboot()
{
    local cur prev words cword
    _init_completion || return
    partition_list="boot bootloader radio recovery system userdata"
    opts="-w -s -p -c -i -b -n -S -h --help --force --slot --set-active --skip-secondary --skip-reboot --disable-verity --disable-verification --fs-options --unbuffered -v --verbose --version"

    case $prev in
        -S|--slot|--dtb|--cmdline|--base|--kernel-offset|--ramdisk-offset|--tags-offset|--dtb-offset|--page-size|--header-version|--os-version|--os-patch-level)
            return      # these options require manual input
            ;;
        -s) # find connected devices
            local devices=$(fastboot devices |cut -f1 |grep -v ' ')
            COMPREPLY=( $(compgen -W "$devices" -- "$cur" ) )
            return
            ;;
    esac

    case "${cur}" in
        -*)
          COMPREPLY=( $(compgen -W "$opts" -- ${cur}) )
          return 0
          ;;
    esac

    local cmd i
    for (( i=1; i < cword; i++ )); do
        if [[ "${words[i]}" != -* && "${words[i-1]}" != -[sp] ]]; then
            cmd="${words[i]}"
            break
        fi
    done

    if [[ ! "$cmd" ]]; then
        local tmp=()
        if [[ ! $cur || $cur != -* ]]; then
            tmp+=( update flash flashall ) # flashing
            tmp+=( devices getvar reboot ) # basics
            tmp+=( flashing )              # lock/unlock
            tmp+=( erase format set_active oem gsi wipe-super create-logical-partition delete-logical-partition resize-logical-partition snapshot-update snapshot-update fetch ) # advanced
            tmp+=( boot flash )            # boot image
            tmp+=( stage get_staged )      # Android Things
        fi
        COMPREPLY=( $(compgen -W '${tmp[@]}' -- "$cur") )
        return
    fi

    case $cmd in
        update)
            _filedir
            ;;
        reboot)
            COMPREPLY=( $(compgen -W 'bootloader' -- "$cur" ) )
            ;;
        fetch|flash|erase)
            COMPREPLY=( $(compgen -W "${partition_list}" -- "$cur" ) )
            ;;
        flashing)
            COMPREPLY=( $(compgen -W '
              lock unlock lock_critical unlock_critical get_unlock_ability
            ' -- "$cur" ) )
            ;;
        gsi)
            COMPREPLY=( $(compgen -W 'wipe disable' -- "$cur" ) )
            ;;
        snapshot-update)
            COMPREPLY=( $(compgen -W 'cancel merge' -- "$cur") )
            ;;
        set_active)
            COMPREPLY=( $(compgen -W 'a b' -- "$cur") )
            ;;
        --slot)
            COMPREPLY=( $(compgen -W 'all other' -- "$cur") )
            ;;
    esac
} &&
complete -F _fastboot fastboot

# ex: filetype=sh
