summaryrefslogtreecommitdiff
path: root/dmount
blob: 8b0b2b7365e8b13b6a72b1f9665ffa5e34bef51f (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/bin/sh

printhelp () {
  printf "tmp\n"
}

show () {
  printf "$@\n"
  notify-send "dmount" "$@"
}

error_msg () {
  show "$@"
  exit 1
}

while getopts "xwhd:" o; do case "${o}" in
  x) DMENU="dmenu" ;;
  w) DMENU="bemenu" ;;
  d) ARGS="$ARGS $OPTARG" ;;
  h)
    printhelp
    exit
    ;;
  *)
    printhelp
    exit 1;;
esac done

if [ -z "$DMENU" ]; then
  if [ -n "$WAYLAND_DISPLAY" ]; then
    DMENU="bemenu"
  elif [ -n "$DISPLAY" ]; then
    DMENU="dmenu"
  else
    error_msg "Can't tell if Wayland or Xorg; is there a display server?"
  fi
fi

case "$DMENU" in
  dmenu) PASSARG="-P" ;;
  bemenu) PASSARG="-x" ;;
esac

check_crypto () {
  [ "$(lsblk -oFSTYPE "$1" | wc -l)" -gt 2 ] && printf "y"
}

is_crypto () {
  lsblk -oFSTYPE "$1" | grep -q "crypto_LUKS" && printf "y"
}

unlock_crypto () {
  NAME="$(cat /dev/null | $DMENU -p "Name" $ARGS)"
  PASSWORD="$(cat /dev/null | $DMENU -p "Password" $PASSARG $ARGS)"
  echo "$PASSWORD" | sudo cryptsetup open "$1" "$NAME" || FAILED="y"
  unset PASSWORD
  [ -n "$FAILED" ] && \
    error_msg "Failed to decrypt partition $1!"
  show "Decrypted $1 successfully."

}

get_available () { lsblk -oPATH,FSTYPE,MOUNTPOINT | tail -n+2 | while read i; do
    [ -z "$(echo "$i" | awk '{print $2}')" ] && continue
    [ -n "$(echo "$i" | awk '{print $3}')" ] && continue
    #echo "${i%% *}"
    #echo "$(lsblk -oMOUNTPOINT "${i%% *}" | tail -n+2 | grep -v -E '^\s*$')"
    [ -n "$(echo "$i" | grep -q "crypto_LUKS" && check_crypto "${i%% *}")" ] \
      && continue
    echo "$i"
  done
}

getmount() { \
  [ -z "$chosen" ] && exit 1
  # shellcheck disable=SC2086
  mp="$(find $1 2>/dev/null | $DMENU -l 10 $ARGS -p "Type in mount point.")" || error_msg "Canceled; no mount point chosen."
  test -z "$mp" && \
    exit 1
  if [ ! -d "$mp" ]; then
    mkdiryn=$(printf "No\\nYes" | $DMENU -l 10 $ARGS -p "$mp does not exist. Create it?") || \
      exit 1
    [ "$mkdiryn" = "Yes" ] && (mkdir -p "$mp" || doas mkdir -p "$mp")
  fi
}

mount_device () {
  getmount "/mnt /media /mount /home -maxdepth 3 -type d -empty $alreadymounted"
  doas mount "$1" "$mp" && show "Mounted successfully\n"
}

DEVICE="$(get_available | $DMENU -p "Devices" $ARGS -l 15)"
[ -z "$DEVICE" ] && exit 1
chosen="${DEVICE%% *}"

if [ -n "$(is_crypto "$chosen")" ]; then
  unlock_crypto "$chosen"
  unset DEVICE chosen DMENU ARGS PASSARG
  dmount
fi

mount_device "$chosen"
unset DEVICE chosen DMENU ARGS PASSARG