| 1 | #!/bin/sh |
| 2 | # Menu to unmount drives and phones mounted with mounter (or anything else on a |
| 3 | # /dev device, except /, /boot, /efi and /home), via udisks and gvfs. LUKS mappers |
| 4 | # are locked again afterwards: automatically if udisks opened them (luks-<uuid>), |
| 5 | # else after asking. |
| 6 | |
| 7 | menu() { aurora-run -d -p "$1"; } |
| 8 | notify() { notify-send -a unmounter "$@"; } |
| 9 | die() { notify -u critical "๐พ Unmount failed" "$1"; exit 1; } |
| 10 | |
| 11 | # kind<TAB>target<TAB>source<TAB>fstype per mount; jq so paths with spaces survive. |
| 12 | # Phones are gvfs mounts: target = their name, source = mtp:// uri. |
| 13 | mounts="$( |
| 14 | findmnt -Jo TARGET,SOURCE,FSTYPE | jq -r ' |
| 15 | .. | objects | select(has("target")) |
| 16 | | select(.source | startswith("/dev/")) |
| 17 | | select(.target | test("^/(boot|efi|home)?$") | not) |
| 18 | | ["drive", .target, (.source | sub("\\[.*"; "")), .fstype] | @tsv' |
| 19 | gio mount -l 2>/dev/null | sed -n 's/^ *Mount([0-9]*): \(.*\) -> \(mtp:\/\/.*\)$/phone\t\1\t\2\tmtp/p' |
| 20 | )" |
| 21 | [ -z "$mounts" ] && { notify "๐พ Unmounter" "Nothing to unmount."; exit 0; } |
| 22 | |
| 23 | i="$(echo "$mounts" | while IFS=" " read -r kind target src fstype; do |
| 24 | case "$kind" in |
| 25 | phone) icon="๐ฑ" ;; |
| 26 | *) [ "$(lsblk -dno TYPE "$src" 2>/dev/null)" = "crypt" ] && icon="๐" || icon="๐พ" ;; |
| 27 | esac |
| 28 | printf '%s %s %s (%s)\n' "$icon" "$target" "$src" "$fstype" |
| 29 | done | aurora-run -d --index -p "Unmount")" || exit 1 |
| 30 | [ "$i" -ge 0 ] 2>/dev/null || exit 1 |
| 31 | IFS=" " read -r kind target src fstype <<EOF |
| 32 | $(echo "$mounts" | sed -n "$((i + 1))p") |
| 33 | EOF |
| 34 | |
| 35 | if [ "$kind" = "phone" ]; then |
| 36 | err="$(gio mount -u "$src" 2>&1)" || die "$err" |
| 37 | notify "๐ฑ Unmounted" "$target" |
| 38 | exit 0 |
| 39 | fi |
| 40 | |
| 41 | err="$(udisksctl unmount -b "$src" 2>&1)" || { |
| 42 | pids="$(fuser -m "$target" 2>/dev/null)" |
| 43 | [ -n "$pids" ] && err="$err |
| 44 | In use by: $(ps -o comm= -p "$(echo $pids | tr ' ' ',')" | sort -u | tr '\n' ' ')" |
| 45 | die "$err" |
| 46 | } |
| 47 | notify "๐พ Unmounted" "$target" |
| 48 | |
| 49 | # Lock the LUKS container behind a mapper, unless it's still mounted somewhere else. |
| 50 | [ "$(lsblk -dno TYPE "$src" 2>/dev/null)" = "crypt" ] || exit 0 |
| 51 | findmnt -n --source "$src" >/dev/null && exit 0 |
| 52 | luks="$(lsblk -nprso NAME "$src" | sed -n 2p)" |
| 53 | [ "$(lsblk -dno FSTYPE "$luks")" = "crypto_LUKS" ] || exit 0 |
| 54 | case "$(basename "$src")" in |
| 55 | luks-*) ;; |
| 56 | *) [ "$(printf 'Yes\nNo' | menu "Also lock $luks ($(basename "$src"))?")" = "Yes" ] || exit 0 ;; |
| 57 | esac |
| 58 | err="$(udisksctl lock -b "$luks" 2>&1)" || die "Could not lock $luks: $err" |
| 59 | notify "๐ Locked" "$luks" |