Krolyxon
Commit 3ce61b8

Branches

Refs →

aurora.localbinunmounter

59 lines ยท 2.4 KB ยท Bourne Again Shell (bash)

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
7menu() { aurora-run -d -p "$1"; }
8notify() { notify-send -a unmounter "$@"; }
9die() { 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.
13mounts="$(
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
23i="$(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"
29done | aurora-run -d --index -p "Unmount")" || exit 1
30[ "$i" -ge 0 ] 2>/dev/null || exit 1
31IFS=" " read -r kind target src fstype <<EOF
32$(echo "$mounts" | sed -n "$((i + 1))p")
33EOF
34
35if [ "$kind" = "phone" ]; then
36 err="$(gio mount -u "$src" 2>&1)" || die "$err"
37 notify "๐Ÿ“ฑ Unmounted" "$target"
38 exit 0
39fi
40
41err="$(udisksctl unmount -b "$src" 2>&1)" || {
42 pids="$(fuser -m "$target" 2>/dev/null)"
43 [ -n "$pids" ] && err="$err
44In use by: $(ps -o comm= -p "$(echo $pids | tr ' ' ',')" | sort -u | tr '\n' ' ')"
45 die "$err"
46}
47notify "๐Ÿ’พ 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
51findmnt -n --source "$src" >/dev/null && exit 0
52luks="$(lsblk -nprso NAME "$src" | sed -n 2p)"
53[ "$(lsblk -dno FSTYPE "$luks")" = "crypto_LUKS" ] || exit 0
54case "$(basename "$src")" in
55 luks-*) ;;
56 *) [ "$(printf 'Yes\nNo' | menu "Also lock $luks ($(basename "$src"))?")" = "Yes" ] || exit 0 ;;
57esac
58err="$(udisksctl lock -b "$luks" 2>&1)" || die "Could not lock $luks: $err"
59notify "๐Ÿ”’ Locked" "$luks"