#!/usr/bin/env sh

loopdir=/usr/local/data/loopdevices
loopfile=$loopdir/crypt.loop

keyfiledir=/usr/local/data/.crypto
keyfile=$keyfiledir/ss_crypto.keyfile

#megabytes
loopsize=16

#/dev/mapper/xxxxx when open
cryptmapper=secStorage

makefilesystem=ext4

#mountpoint of uncrypted device
mountpoint=/usr/local/data/secure-storage

create_keyfile() {
	# echo "Create key file"
	systemd-notify --status="Create key file"
	mkdir -p $keyfiledir
	dd if=/dev/urandom of=$keyfile bs=1 count=256
	chown root:root $keyfiledir/*
	chmod 000 $keyfiledir/*
}

error() {
	echo "Error: $1"
	exit $?
}

#creates a new file
create_loopback_and_open() {
	# echo "Creating a file with random bits.. this could take a while..."
	systemd-notify --status="Creating a file with random bits.. this could take a while..."
	mkdir -p $loopdir || error "Creating loopdir"
	mkdir -p $mountpoint || error "Creating mountpoint"
	dd if=/dev/urandom of=$loopfile bs=1M count=$loopsize || error "Creating loopfile"
	loopdevice=$(losetup -f --show $loopfile) || error "Setting up loop device"
	echo "Selected loop device: $loopdevice"
	cryptsetup luksFormat -q --key-file $keyfile $loopdevice || error "Setting up encrypted loop device"
	cryptsetup open --key-file $keyfile $loopdevice $cryptmapper || error "Opening encrypted loop device"
	mkfs.$makefilesystem /dev/mapper/$cryptmapper || error "Creating encrypted FS"
	mount /dev/mapper/$cryptmapper $mountpoint || error "Mounting encrypted FS"
	systemd-notify --ready --status="Sucessfully mounted secure storage"
}

#mounts crypted loopback file
open() {
	#echo "Open secure-storage"
	systemd-notify --status="Open secure storage"
	loopdevice=$(losetup -f --show $loopfile) || error "Setting up loop device"
	echo "Selected loop device: $ld"
	cryptsetup open --key-file $keyfile $loopdevice $cryptmapper || error "Opening encrypted loop device"
	mount /dev/mapper/$cryptmapper $mountpoint || error "Mounting encrypted FS"
	systemd-notify --ready --status="Sucessfully mounted secure storage"
}

#unmounts previously mounted loopback file
close() {
	echo "Close secure-storage"
	# get loopdevice
	loopdevice=$(losetup --list --noheadings --output NAME,BACK-FILE | grep crypt.loop | awk '{print $1}')
	umount $mountpoint
	cryptsetup close $cryptmapper
	losetup -d $loopdevice
}

if [ $# -eq 1 ]
then
	#echo "Parameter detected"
	$1
	exit 0
fi

if [ -e $keyfile ]
then
	#echo "Key file available"
	if [ -e $loopfile ]
	then
		#echo "Loop file available"
		open
	else
		#echo "Loop file not available"
		create_loopback_and_open
	fi
else
	#echo "Key file not available"
	create_keyfile
	create_loopback_and_open
fi
