#!/bin/bash

sudo echo ">>> Initialising"

METADIR=~/.etemp
MOUNTPOINT=~/etemp
VOLNAME=etemp

if [[ ! -d "$METADIR" ]]; then
	mkdir "$METADIR"
fi

if stat /dev/mapper/$VOLNAME &> /dev/null; then
	echo "ERROR: /dev/mapper/$VOLNAME already exists. Please close the volume first."
	exit 1
fi

if [[ `id -u` == 0 ]]; then
	echo "WARNING: Running as root? This might not be what you want."
fi

if [[ -d "$MOUNTPOINT" ]]; then
	rmdir "$MOUNTPOINT" || { echo "ERROR: Mount point $MOUNTPOINT is not empty"; exit 1; }
fi

mkdir "$MOUNTPOINT" || { echo "ERROR: Could not create mountpoint at $MOUNTPOINT"; exit 1; }

if [[ -f "$METADIR/image" ]]; then
	echo "WARNING: Image already exists"
	read -p "Create anyway (y/N)? " -n 1 -r
	echo
	if [[ $REPLY =~ ^[Yy]$ ]]; then
		rm "$METADIR/image" || exit 1
	else
		echo "Doing nothing."
		exit 0
	fi
fi

SIZE=$1

if [[ ! "$SIZE" =~ ^[0-9]+[KkMmGg]?$ ]]; then
	SIZE=1G
	echo "WARNING: Size not provided, going with default ($SIZE)"
fi

echo ">>> Generating key"

KEY=$(dd if=/dev/urandom bs=3 status=none count=256 | base64)

echo "Will create container $METADIR/image and mount /dev/mapper/$VOLNAME at $MOUNTPOINT"
read -p "Is this okay (y/N)? " -n 1 -r
echo

[[ $REPLY =~ ^[Yy]$ ]] || exit 1

echo ">>> Creating container"

fallocate -l $SIZE "$METADIR/image"

echo ">>> Formatting container"

echo $KEY | sudo cryptsetup luksFormat "$METADIR/image" -d -
echo $KEY | sudo cryptsetup luksOpen "$METADIR/image" $VOLNAME -d -

echo ">>> Creating filesystem"

sudo mkfs.ext4 /dev/mapper/$VOLNAME

echo ">>> Mounting volume to $MOUNTPOINT"

sudo mount /dev/mapper/$VOLNAME "$MOUNTPOINT"
sudo chown `whoami` "$MOUNTPOINT"

echo "Done."