#!/bin/sh

set -e

# tomb writes non-error output to stderr, we redirect it to stdout by 2>&1.
TOMB=/usr/bin/tomb

# Create a file to hold an encrypted file system and drop it right away. 
zsh -e $TOMB dig -s 20 test.tomb 2>&1
rm test.tomb
# Create a pbkdf2 key file making sure the kdf binaries are used during key
# generation by applying --kdf.
zsh -e $TOMB forge --unsafe -f --tomb-pwd somepw --kdf 1 pbkdf2-test.key 2>&1
# Create an argon2 key file
zsh -e $TOMB forge --unsafe -f --tomb-pwd somepw --kdf 1 argon2-test.key --kdftype argon2 2>&1

# 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 ...
	zsh -e $TOMB dig -s $fssize test.tomb 2>&1
	zsh -e $TOMB lock --unsafe -f --tomb-pwd somepw -k $keytype-test.key --filesystem $fstype test.tomb 2>&1
	zsh -e $TOMB open --unsafe -f --tomb-pwd somepw -k $keytype-test.key test.tomb 2>&1
	echo Copying some data into the opened tomb ...
	cp -a *-test.key /media/test
	echo Opened tomb\'s content:
	ls -la /media/test
	zsh -e $TOMB close test 2>&1
	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
