dotfiles/scripts/dmenu-udevil.sh

119 lines
3.2 KiB
Bash
Executable File

#!/usr/bin/env sh
DMENU=${DMENU:-dmenu}
DEV_LABEL="/dev/disk/by-label/"
TMP="/tmp/dmnt-udevil-$(date +%s)"
trap "rm -f $TMP" EXIT
opt_mount_type=0
opt_ignore_filter=0
opt_notify=0
udevil_cmd="mount"
usage() {
cat <<-EOF
usage: dmenu-udevil [-mudihn]
-m Mount devices
-u Unmount devices
-d Select by device rather than by label
-i Ignore filter and list all devices in /dev (with -d)
-n Pass udevil output to notify-send
-h Print help
EOF
}
dmenu_mnt() {
if [ $opt_mount_type -eq 1 ]; then
prompt="$udevil_cmd by-device:"
if [ $opt_ignore_filter -eq 0 ]; then
res="$(find /dev -maxdepth 1 -not -type d -name "s[dr]*" -or \
-name "hd*" | cut -d'/' -f3 | ${DMENU} -i -p "$prompt")"
else
res="$(find /dev -maxdepth 1 -not -type d | cut -d'/' -f3 | \
${DMENU} -i -p "$prompt")"
fi
path="/dev/$res"
[ -z $res ] && printf "%b\n" "Cancelled." && exit
else
prompt="$udevil_cmd by-label:"
res="$(find $DEV_LABEL* | cut -d'/' -f5 | ${DMENU} -i -p "$prompt")"
path="$DEV_LABEL/$res"
[ -z $res ] && printf "%b\n" "Cancelled." && exit
fi
printf "%b\n" "udevil $udevil_cmd "$path" > "$TMP" 2>&1"
udevil $udevil_cmd "$path" > "$TMP" 2>&1
exitc=$?
if [ $opt_notify -eq 1 ]; then
case $exitc in
0) urgency="normal";;
*) urgency="critical";;
esac
notify-send -u $urgency "$(cat $TMP)"
else
cat "$TMP"
fi
}
mountandroid() { \
chosen=$(printf "%b\n" "$anddrives" | dmenu -i -p "Which Android device?" | cut -d : -f 1)
# getmount "$HOME -maxdepth 3 -type d"
simple-mtpfs --device "$chosen" "$ANDROID_MOUNTPOINT"
notify-send "🤖 Android Mounting" "Android device mounted to $ANDROID_MOUNTPOINT."
}
umountandroid() { \
chosen=$(awk '/simple-mtpfs/ {print $2}' /etc/mtab | \
dmenu -i -p "Unmount which device?")
[ -z "$chosen" ] && exit
# sudo -A umount -l "$chosen" && notify-send "🤖 Android unmounting" "$chosen unmounted."
fusermount -u "$chosen" \
&& notify-send "🤖 Android unmounting" "$chosen unmounted."
}
asktype() { \
case $(printf "%b\n" "USB\\nAndroid" | dmenu -i -p "Mount a USB drive or Android device?") in
USB) dmenu_mnt ;;
Android) [ "$udevil_cmd" = "mount" ] && mountandroid || umountandroid ;;
esac
}
while getopts ':mudhin' opt; do
case "$opt" in
m) ;;
u) udevil_cmd="umount";;
d) opt_mount_type=1;;
i) opt_ignore_filter=1;;
h) usage && exit;;
n) opt_notify=1;;
/?) printf "%b\n" "Unrecognized command: $OPTARG";;
esac
done
anddrives=$(simple-mtpfs -l 2>/dev/null)
usbdrives="$(lsblk -rpo "name,type,size,mountpoint" | awk '$2=="part"&&$4==""{printf "%b\n" "%s (%s)\n",$1,$3}')"
if [ -z "$usbdrives" ]; then
[ -z "$anddrives" ] && notify-send "No USB drive or Android device detected" && exit
notify-send "Android device(s) detected."
[ "$udevil_cmd" = "mount" ] && mountandroid || umountandroid
else
if [ -z "$anddrives" ]; then
notify-send "USB drive(s) detected."
dmenu_mnt
else
notify-send "Mountable USB drive(s) and Android device(s) detected."
asktype
fi
fi
# dmenu_mnt && exit