#! @bash@/bin/sh

set -e

# e.g /dev/sdb
USB_DEVICE=$1

if echo "$USB_DEVICE" | grep -q "[0-9]$"; then
    PARTITION_SEPARATOR="p"
else
    PARTITION_SEPARATOR=""
fi

if [ -z "$USB_DEVICE" ]; then
  echo "Please specify a path to device as first argument"
  exit 1
fi

if [ "$EUID" -ne 0 ]; then
  echo "Please run as root"
  exit
fi

# encrypted partition label
USB_ENCRYPTED_PARTLABEL=@USB_ENCRYPTED_PARTLABEL@
# unencrypted filesystem label
USB_UNENCRYPTED_LABEL=@USB_UNENCRYPTED_LABEL@

echo "Creating Encrypted USB."

echo "Creating Partitions..."
@parted@/bin/parted ${USB_DEVICE} -- mklabel gpt
@parted@/bin/parted ${USB_DEVICE} -- mkpart primary 0% 100%

echo "Creating Encrypted Partition"
@cryptsetup@/bin/cryptsetup luksFormat "${USB_DEVICE}${PARTITION_SEPARATOR}1"

echo "Opening Encrypted Partition"
@cryptsetup@/bin/cryptsetup open "${USB_DEVICE}${PARTITION_SEPARATOR}1" "mk_enc_usb"

echo "Making Encrypted Filesystem"
@e2fsprogs@/bin/mkfs.ext4 -L "${USB_UNENCRYPTED_LABEL}" /dev/mapper/mk_enc_usb

echo "Closing Encrypted Partition"
@cryptsetup@/bin/cryptsetup close "mk_enc_usb"

# Do this now so that i can run the damn script with usb-automount and stop it trying to mount
echo "Naming Partitions"
@parted@/bin/parted ${USB_DEVICE} -- name 1 "${USB_ENCRYPTED_PARTLABEL}"