#!/usr/bin/env fish

set -g drives (lsblk -nrpo "name,type,size,mountpoint" | \
awk '$2=="part"&&$4!~/\/boot|\/home$|SWAP/&&length($4)>1{printf "%s (%s)\n",$4,$3}')

set -g androids (awk '/jmtpfs/ {print $2}' /etc/mtab)

set -g cds (awk '/sr0/ {print $2}' /etc/mtab)

set -g undrivefile /tmp/undrives

rm -f $undrivefile
touch $undrivefile

test -n "$drives" && echo "USB" >> $undrivefile
test -n "$cds" && echo "CD" >> $undrivefile
test -n "$androids" && echo "Android" >> $undrivefile

function unmountusb

set chosen (echo $drives | \
rofi -dmenu -i -p "Unmount which drive?" | \
awk '{print $1}')

test -z "$chosen" && exit 0

sudo -A umount $chosen && \
notify-send "💻 USB unmounting" "$chosen unmounted." -a "dumount" || \
notify-send "💻 USB unmounting" "$chosen unmounting failed." -a "dumount"

end

function unmountandroid

set chosen (echo $androids | rofi -dmenu -i -p "Unmount which device?")

test -z "$chosen" && exit 0

sudo -A umount -l $chosen && |
notify-send "🤖 Android unmounting" "$chosen unmounted." -a "dumount" || \
notify-send "🤖 Android unmounting" "$chosen failed to unmount." -a "dumount"

end

function unmountcd

set chosen (echo "$cds" | rofi -dmenu -i -p "Unmount which CD?")

test -z "$chosen" && exit 0

sudo -A umount -l $chosen && \
notify-send "💿 CD unmounting" "$chosen unmounted." -a "dumount" || \
notify-send "💿 CD unmounting" "$chosen failed to unmount." -a "dumount"

end

function asktype

switch (cat $undrivefile | rofi -dmenu -i -p "Unmount which type of device?")

case 'USB'
    unmountusb
case 'CD'
    unmountcd
case 'Android'
    unmountandroid

end

end

switch (wc -l < $undrivefile)

case 0
    notify-send "No USB drive or Android device or CD to unmount" -a "dumount"

case 1
    switch (cat $undrivefile)
        case 'USB'
            unmountusb
        case 'CD'
            unmountcd
        case 'Android'
            unmountandroid
    end

case '*'
     asktype

end

rm -f $undrivefile