#!/bin/sh

# a simple dmenu usb managment script

load_config () {
    . $HOME/.config/dmenu/config
}

driveCount(){
    count="$(printf '%s\n' "$1" | wc -l)"
}

mount(){
    mountable="$(lsblk -lp | awk '/^\/dev\/sd.*part $/ { print $1 " ("$4")" }')"

    if [ "$mountable" = "" ]; then
        quick-notify "$DMENU Usb Manager" "No drives to mount"
        exit
    fi

    chosen="$(printf '%s' "$mountable" | $DMENU -p "Drive to mount?")"

    if [ -n "$chosen" ];then
        udisksctl mount -b "${chosen%% *}"
        quick-notify "Dmenu Usb Manager" "Drive ${chosen%% *} mounted"
    else
        quick-notify "Dmenu Usb Manager" "No drives chosen to mount" 
        exit
    fi

}

unmount(){
    mounted="$(lsblk -lp | awk '/run/ { print $1 " ("$4")" }')"
 
    if [ "$mounted" = "" ]; then
        quick-notify "Dmenu Usb Manager" "No drives to unmount"
        exit
    fi

    chosen="$(printf "$mounted" | $DMENU -p "Drive to unmount?")"

    if [ -n "$chosen" ];then
        udisksctl unmount -b "${chosen%% *}"
        quick-notify "Dmenu Usb Manager" "Drive ${chosen%% *} unmounted"
    else
        quick-notify "Dmenu Usb Manager" "No drives chosen to unmount" 
        exit
    fi
}

menu () {
    case $(printf "mount\\nunmount" | $DMENU -p "Chose your usb action") in
        "mount") mount ;;
        "unmount") unmount ;;
    esac
}

main () {
    load_config

    menu
}

main $@