#!/bin/sh

set -e

TOMB=/usr/bin/tomb
CLOAK_CIPHER=/usr/share/doc/tomb/examples/cloak-ciphers/emoji

echo ~~ Create a file to hold an encrypted file system ...
# ... and drop it right away. 
$TOMB dig -s 20 test.tomb
rm test.tomb
echo ~~ Create a pbkdf2 key file ...
# ... making sure the kdf binaries are used during key generation
$TOMB forge --unsafe -f --tomb-pwd somepw --kdf pbkdf2 pbkdf2-test.key
echo ~~ Create an argon2 key file ...
$TOMB forge --unsafe -f --tomb-pwd somepw --kdf argon2 argon2-test.key
echo ~~ Cloak a key file ...
$TOMB cloak -k argon2-test.key $CLOAK_CIPHER cloaked_key.txt
echo ~~ Uncloak and verify a key file ...
$TOMB uncloak cloaked_key.txt $CLOAK_CIPHER uncloaked.key
cmp argon2-test.key uncloaked.key
rm uncloaked.key

# Stop test here if the environment has no loop device available
if ! ls /dev/loop-control >/dev/null 2>&1; then
	echo No loop device available, cutting test short.
	exit 0
fi
# Continue tests with commands requiring a loop device

# Function to create an encrypted file system write to it and drop it.
create_write_drop () {
	local fstype=$1 fssize=$2 keytype=$3

	echo ~~ Testing $fstype file system using a $keytype key ...
	$TOMB dig -s $fssize test.tomb
	$TOMB lock --unsafe -f --tomb-pwd somepw -k $keytype-test.key --filesystem $fstype test.tomb
	$TOMB open --unsafe -f --tomb-pwd somepw -k $keytype-test.key test.tomb
	echo ~~ Copying some data into the opened tomb ...
	cp -a *-test.key /media/test
	echo ~~ Opened tomb\'s content is ...
	ls -la /media/test
	$TOMB close test
	rm test.tomb
}

# Test various file systems and keys
create_write_drop ext4 20 pbkdf2
create_write_drop ext4 20 argon2
create_write_drop btrfs 115 pbkdf2
create_write_drop btrfsmixedmode 20 argon2
