#!/bin/bash
# /etc/bash_completion.d/velvettools

get_available_kernel_versions(){
    ls -1 /boot/Image-* | sed "s|/boot/Image-||g"
}

# vtpack
_vt_pack_completion() {
    local curr_arg="${COMP_WORDS[COMP_CWORD]}"

    local options=""

    case "$COMP_CWORD" in

    "1")
        options="deb targz dir"
        ;;

    "2")
        options=$(get_available_kernel_versions)
        ;;
    "3")
        if [ "${COMP_WORDS[1]}" == "deb" ];then
            options=$(logname)
        fi
        ;;
    esac

    COMPREPLY=($(compgen -W "$options" -- "$curr_arg"))
}
complete -F _vt_pack_completion vtpack

# vttest and vtflash
_vt_flash_completion() {
    local curr_arg="${COMP_WORDS[COMP_CWORD]}"

    local options=""

    case "$COMP_CWORD" in

    "1")
        options=$(get_available_kernel_versions)
        ;;

    "2")
        options=$(ls -d /dev/*)
        ;;
    esac

    COMPREPLY=($(compgen -W "$options" -- "$curr_arg"))
}
complete -F _vt_flash_completion vtflash
complete -F _vt_flash_completion vttest
complete -F _vt_flash_completion vtdisable

# vtdisable
_vt_disk_completion() {
    local curr_arg="${COMP_WORDS[COMP_CWORD]}"

    local options=""

    if [ "$COMP_CWORD" == "1" ];then
        options=$(ls -d /dev/*)
    fi

    COMPREPLY=($(compgen -W "$options" -- "$curr_arg"))
}
complete -F _vt_disk_completion vtdisable

# vtbuild
_vt_build_completion() {
    local curr_arg="${COMP_WORDS[COMP_CWORD]}"

    local options=""

    case "$COMP_CWORD" in

    "1")
        options=$(get_available_kernel_versions)
        ;;

    "2")
        options="noinitgen"
        ;;
    esac


    COMPREPLY=($(compgen -W "$options" -- "$curr_arg"))
}
complete -F _vt_build_completion vtbuild

# vtremove
_vt_remove_completion() {
    local curr_arg="${COMP_WORDS[COMP_CWORD]}"

    local options=""

    if [ "$COMP_CWORD" == "1" ];then
        options=$(get_available_kernel_versions)
    fi

    COMPREPLY=($(compgen -W "$options" -- "$curr_arg"))
}
complete -F _vt_remove_completion vtremove

# vthelp
_vt_help_completion() {
    local curr_arg="${COMP_WORDS[COMP_CWORD]}"

    local options=""

    if [ "$COMP_CWORD" == "1" ];then
        options=$(ls /usr/share/velvettools/help)
    fi

    COMPREPLY=($(compgen -W "$options" -- "$curr_arg"))
}

complete -F _vt_help_completion vthelp


install_root_device(){
    lsblk --raw -d -no PKNAME $(findmnt / --raw -no SOURCE)
}

install_valid_devices(){
    lsblk -d --raw -no NAME | grep -v mtd | grep -v $(install_root_device) | grep -v boot
}

_vt_install_completion() {
    local curr_arg="${COMP_WORDS[COMP_CWORD]}"

    local options=""

    if [ "$COMP_CWORD" == "1" ];then
        options="$(install_valid_devices | tr '\n' ' ')"
    fi

    COMPREPLY=($(compgen -W "$options" -- "$curr_arg"))
}

complete -F _vt_install_completion vtinstall
