summaryrefslogtreecommitdiff
path: root/ar/.local/bin/unmounter
blob: 537fd250b83cf8ed153460885909740bc0791f5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/bin/sh

# Unmount USB drives or Android phones. Replaces the older `dmenuumount`. Fewer
# prompt and also de-decrypts LUKS drives that are unmounted.

set -e

mounteddroids="$(grep simple-mtpfs /etc/mtab | awk '{print "📱" $2}')"
mountedios="$(grep ifuse /etc/mtab | awk '{print "🍎" $2}')"
lsblkoutput="$(lsblk -nrpo "name,type,size,mountpoint")"
mounteddrives="$(echo "$lsblkoutput" | awk '($2=="part"||$2="crypt")&&$4!~/\/boot|\/home$|SWAP/&&length($4)>1{printf "💾%s (%s)\n",$4,$3}')"
mountedcifs="$(grep cifs /etc/mtab | awk '{print "🪟" $2}')"

allunmountable="$(echo "$mounteddroids
$mountedios
$mounteddrives
$mountedcifs" | sed "/^$/d;s/ *$//")"
test -n "$allunmountable"

chosen="$(echo "$allunmountable" | dmenu -i -p "Unmount which drive?")"
chosen="${chosen%% *}"
test -n "$chosen"

label=$(df "/${chosen#*/}" | tail -n 1 | awk '{print $1}' | xargs -I {} sudo blkid {} | awk -F '\"' '{print $2}')
if [ -n "$label" ]; then
  mountpath="$(sudo lsblk -no "mountpoints" "$(df "/${chosen#*/}" | tail -n 1 | awk '{print $1}')")"
  sudo -A umount -l "/${chosen#*/}"
  notify-send "⏏️ Device unmounted." "$chosen has been unmounted."
  if [ "/media/$USER/${chosen##*/}" = "/${chosen#*/}" ] &&
    [ "${chosen##*/}" = "$label" ] &&
    [ "/media/$USER/${chosen##*/}" = "$mountpath" ] &&
    [ -e "/${chosen#*/}" ] &&
    [ ! -s "/${chosen#*/}" ]; then
    chosen="/${chosen#*/}"
    rm -r "${chosen:?}" >/dev/null 2>&1 || sudo -A rm -r "${chosen:?}"
    notify-send "🚮 Mounted path removed." "$chosen has been removed."
  fi
else
  if grep -q "/${chosen#*/}" /etc/mtab | grep -qE "cifs" /etc/mtab; then
    sudo -A umount "/${chosen#*/}"
    notify-send "⏏️ SMB Drive unmounted." "/${chosen#*/} has been unmounted."
  elif grep -q "/${chosen#*/}" /etc/mtab | grep -q "ifus" /etc/mtab; then
    sudo -A umount "/${chosen#*/}"
    notify-send "⏏️ IOS Drive unmounted." "/${chosen#*/} has been unmounted."
  fi
  chosen="/${chosen#*/}"
  [ -e "$chosen" ] && [ ! -s "$chosen" ] &&
    sudo -A rm -r "${chosen:?}" &&
    notify-send "🚮 Mounted path removed." "$chosen has been removed."
fi

# Close the chosen drive if decrypted.
cryptid="$(echo "$lsblkoutput" | grep "/${chosen#*/}$")"
cryptid="${cryptid%% *}"
test -b /dev/mapper/"${cryptid##*/}"
sudo -A cryptsetup close "$cryptid"
notify-send "🔒 Device dencryption closed." "Drive is now securely locked again."