aboutsummaryrefslogtreecommitdiffstats
path: root/bin/cs
blob: 4eb7fe67b906ffe338f6e4c6695d605c646426d4 (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
#! /usr/bin/env bash

set -euo pipefail

declare -A devices
valid_name=0
command_name=${1:-}
device_name=${2:-}

if [ -r "$HOME/.config/cs/config" ]; then
  . "$HOME/.config/cs/config"
fi
#TODO: do sanity checks on mountpoints and (dm) devices
#TODO: display list of devices available, if no argument given

function open_cryptdevice() {
  if [ -L "/dev/disk/by-uuid/$1" ]; then
    if [ -L "/dev/mapper/$2" ]; then
      echo "Crypt device has already been opened: /dev/mapper/$2"
      echo "Continuing..."
    else
      /usr/bin/sudo /usr/bin/cryptsetup luksOpen "/dev/disk/by-uuid/$1" "$2"
    fi
  else
    echo "Error: Device $2 (UUID=$1) is not available."
    return 1
  fi
}

function close_cryptdevice() {
  /usr/bin/sudo /usr/bin/cryptsetup luksClose "$1"
}

function mount_cryptdevice() {
  if [[ -e "/dev/mapper/$1" ]]; then
    if [[ ! -d "/mnt/$1" ]]; then
      sudo mkdir -p "/mnt/$1"
    fi
    sudo mount "/dev/mapper/$1" "/mnt/$1"
    if [ -x "$HOME/.config/cs/post_mount/$1" ]; then
      "$HOME/.config/cs/post_mount/$1"
    fi
  else
    echo "Error: Device /dev/mapper/$1 is not available."
    return 1
  fi
}

function unmount_cryptdevice() {
  if [ -x "$HOME/.config/cs/pre_umount/$1" ]; then
    "$HOME/.config/cs/pre_umount/$1"
  fi
  /usr/bin/sudo /usr/bin/umount "/mnt/$1"
}

function validate_cryptdevice_name() {
  local _result_valid_name="$1"
  local name_found=0
  local input_name="${2:-}"
  for name in "${!devices[@]}"; do
    if [ "$name" = "${input_name}" ]; then
      name_found=1
      eval "$_result_valid_name"="$name_found"
    fi
  done
}

validate_cryptdevice_name valid_name "${device_name}"
if [ $valid_name -eq 0 ]; then
  echo "No such device: '$device_name'!"
  exit 1
fi

case "$command_name" in
  "open")
    open_cryptdevice "${devices[${2}]}" "$2"
    mount_cryptdevice "$2"
    ;;
  "close")
    unmount_cryptdevice "$2"
    close_cryptdevice "$2"
    ;;
  *)
    echo "cs only understands 'open' and 'close'."
    exit 1
    ;;
esac

exit 0