#!/bin/sh

# encrypt_usb.sh
# 2014-12-11
# by Gernot Walzl

# create encrypted container

print_usage () {
  echo "Usage: $0 {create USBDEV, mount USBDEV, umount}"
}

create () {
  local USBDEV=$1
  local LABEL=$2

  if [ "$(lsscsi -t | grep usb | grep ${USBDEV})" = "" ]; then
    echo "ERROR: $USBDEV is not an usb device."
    exit 1
  fi

  cfdisk "$USBDEV"  # 50% vfat = 0C ; 50% linux = 83

  mkfs.vfat "${USBDEV}1"
  if [ ! -z "$LABEL" ]; then
    mlabel -i "${USBDEV}1" "::${LABEL}"
  fi

  cryptsetup luksFormat "${USBDEV}2"
  cryptsetup luksOpen "${USBDEV}2" usb-crypt
  mkfs.ext4 /dev/mapper/usb-crypt
  cryptsetup luksClose usb-crypt
}

mount () {
  local USBDEV=$1
  cryptsetup luksOpen "${USBDEV}2" usb-crypt
  mount /dev/mapper/usb-crypt /mnt/tmp
}

umount () {
  umount /mnt/tmp
  cryptsetup luksClose usb-crypt
}

case "$1" in
 'create')
  create $2
  ;;
 'mount')
  mount $2
  ;;
 'umount')
  umount
  ;;
 *)
  print_usage
esac