#!/bin/sh

set -e

cd ${AUTOPKGTEST_TMP:-/tmp}

#verbose="--verbose --debug --debug-json"
verbose="--verbose"

echo ">> Setup the 'cryptedfs' file that will contain the luks container"
dd if=/dev/zero of=cryptedfs count=1 bs=20M
echo -n "this the passphrase" >keyfile-default
echo -n "nuke-it" >keyfile-nuke

echo ">> Format with cryptsetup"
cryptsetup --batch-mode $verbose --use-urandom luksFormat cryptedfs keyfile-default

echo ">> Add nuke passphrase"
mkdir -p /etc/cryptsetup-nuke-password
cat keyfile-nuke | /usr/lib/cryptsetup-nuke-password/crypt --generate \
    >/etc/cryptsetup-nuke-password/password_hash

echo ">> Open the luks container"
cryptsetup $verbose open cryptedfs testnuke --key-file keyfile-default
if [ ! -e /dev/mapper/testnuke ]; then
    echo "ERROR: /dev/mapper/testnuke has not been created"
    exit 1
fi

echo ">> Create the initial filesystem and put a flag file on it"
mkfs.ext4 /dev/mapper/testnuke
mount /dev/mapper/testnuke /mnt
echo "Debian rules!" >/mnt/my-secret-file
umount /mnt
cryptsetup $verbose close testnuke

echo ">> Backup the luks header"
rm -f luks-header-backup
cryptsetup $verbose luksHeaderBackup cryptedfs --header-backup-file luks-header-backup

echo ">> Call askpass with the nuke password"
export CRYPTTAB_SOURCE="$(pwd)/cryptedfs"
export DIVERTED_ASKPASS="$(pwd)/askpass"
cat >$DIVERTED_ASKPASS <<END
#!/bin/sh
cat keyfile-nuke
END
chmod 755 $DIVERTED_ASKPASS
password=$(/lib/cryptsetup/askpass)
if [ "$password" != "nuke-it" ]; then
    echo "ERROR: askpass did not print the expected password on stdout (expected: 'nuke-it', was: '$password')"
    exit 1
fi

echo ">> Ensuring that we can no longer open the luks container"
cryptsetup $verbose open cryptedfs testnuke --key-file keyfile-default || RESULT=$?
if [ $RESULT = 0 ]; then
    echo "ERROR: open with nuke password worked!"
    set +e
    mount /dev/mapper/testnuke /mnt
    if [ -e /mnt/my-secret-file ]; then
	echo "ERROR: and the flag file can be seen"
    fi
    umount /mnt
    cryptsetup $verbose close testnuke
    exit 1
fi
if [ -e /dev/mapper/testnuke ]; then
    echo "ERROR: /dev/mapper/testnuke should not exist"
    cryptsetup $verbose close testnuke
    exit 1
fi
