#!/usr/bin/env bash

if ! [[ "$(uname -s)" =~ Linux ]]; then
	echo "This test currently only runs on Linux."
	exit 77
fi

if [ "$(id -u)" -ne 0 ]; then
	echo "Need to be root to run this test."
	exit 77
fi

STATEDIR="$(mktemp -d)" || exit 1
STATEIMG=$STATEDIR/tpm2.img
STATEFILE=""

trap "cleanup" SIGTERM EXIT
function cleanup()
{
	rm -rf "$STATEDIR"
	if [ -n "$STATEFILE" ]; then
		losetup -d "$STATEFILE"
	fi
}

if [ -z "$(type -P fallocate)" ]; then
	echo "This test requires the fallocate tool."
	exit 77
fi

if ! fallocate --help 2>&1 | grep -q -E "\--posix"; then
	echo "This test requires fallocate to support --posix."
	exit 77
fi

if [ -z "$(type -P losetup)" ]; then
	echo "This test requires the losetup tool."
	exit 77
fi

# allocate 4 MiB file
fallocate --posix -l $((4 * 1024 * 1024)) "$STATEIMG"
# and loop mount it
STATEFILE=$(losetup --show -f "$STATEIMG")

export SWTPM_TEST_LINEAR_FILE=1
export TPM_COMMAND_PORT=65462
export STATEFILE

# don't exec so cleanup will remove the loop device
"$(dirname "$0")/test_tpm2_save_load_state_2"
