#!/bin/sh
# Copyright (C) 2021 Jake Bauer
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# Present the user with a dmenu prompt of mounted devices and umount the
# selected device.
# This script must be run with root privs.
if [ "$(id -u)" -ne 0 ]
then echo "You must run this script with root privileges."
exit 1
fi
disks=$(sysctl hw.disknames | cut -d= -f2 | tr ',' ' ')
for entry in $disks; do
disk="$(echo "$entry" | cut -d: -f1)"
devices="$devices
$(disklabel -p G "$disk" | tail -n +19 | awk -v d=$disk '$9!~/\/boot|\/home$|\/usr|\/var/ {printf "%s%s (%s)\n", d, $1, $2}')"
done
devices=$(echo "$devices" | sed '/^$/d')
choice="$(echo "$devices" | dmenu -i -l 20 -p "Unmount:")" || exit 1
choice="$(echo "$choice" | awk '{print $1}' | tr -d ':')"
umount /mnt/"$choice" && notify-send "Unounted Drive" \
"$choice from /mnt/$choice" && unmounted=1
# Clean up after successful unmount
if [ "$unmounted" ]; then
rmdir /mnt/"$choice"
exit 0
else
notify-send -u critical "Failed to Unmount" \
"Could not unmount $choice: device is busy or not mounted."
exit 1
fi