#!/bin/sh

set -e

. ./helpers

ME=$(basename $0)

# mktemp -t creates the switch mount point folders inside TMPDIR: point
# it to the sandbox, so that the test can assert that a failed run
# doesn't leak any of them behind, and that the cleanup trap detached
# the partition mapping and loop device.
setup_sandbox
TMPDIR=${SANDBOX}/tmp
export TMPDIR
mkdir -p "${TMPDIR}"
export IKV_MOCK_KPARTX_LOG=${SANDBOX}/kpartx.log
export IKV_MOCK_LOSETUP_LOG=${SANDBOX}/losetup.log
: >"${IKV_MOCK_KPARTX_LOG}"
: >"${IKV_MOCK_LOSETUP_LOG}"

leaked_mount_points () {
	ls "${TMPDIR}" | grep -c "switch-mounted-partition" || true
}

# A simulated mount failure, in the middle of the template
# customization of the first switch: the cleanup trap must remove the
# mount point, and detach the partition mapping and loop device.
export IKV_MOCK_FAIL_MOUNT=1
run_setup start
unset IKV_MOCK_FAIL_MOUNT

assert_eq "start rc on mount failure" "${SETUP_RC}" "1"
assert_contains "failure visible in output" "${OUT}" "Simulated mount failure"
assert_eq "no leaked mount point folder" "$(leaked_mount_points)" "0"
assert_contains "trap detached the partition mapping" \
	"$(cat "${IKV_MOCK_KPARTX_LOG}")" "-d /dev/loop0p1"
assert_contains "trap detached the loop device" \
	"$(cat "${IKV_MOCK_LOSETUP_LOG}")" "-d /dev/loop0"

# A normal run must still succeed, and the EXIT trap must not do any
# redundant cleanup, as the script resets the values after each VM.
: >"${IKV_MOCK_KPARTX_LOG}"
: >"${IKV_MOCK_LOSETUP_LOG}"
run_setup start
assert_eq "start rc" "${SETUP_RC}" "0"
assert_eq "no leaked mount point folder" "$(leaked_mount_points)" "0"
assert_eq "trap didn't run on success" \
	"$(grep -c "/dev/loop0p1" "${IKV_MOCK_KPARTX_LOG}" || true)" "0"
assert_eq "trap didn't touch losetup on success" \
	"$(wc -l <"${IKV_MOCK_LOSETUP_LOG}")" "0"

echo "${ME}: all assertions passed."
