#!/bin/bash

set -e

ROUNDS="$1"

if [ "${ROUNDS:-0}" -lt 1 ] ; then
	echo "Usage:"
	echo "$0 INTEGER"
	echo "Run the test for given number of rounds."
	exit 1
fi

if [ "$EUID" != "0" ] ; then
	echo "This script requires root."
	exit 1
fi

TESTIMG="/tmp/test.img"

SCRIPT="
label: gpt

start=2048, size=512MiB, type=uefi,
type=linux,
"

if [ ! -e "$TESTIMG" ] ; then
	echo "[+] Creating test image ..."
	dd if=/dev/zero of="$TESTIMG" bs=128M count=64 status=progress
fi

LOOPDEV="$(losetup -f)"
echo "[+] Loop device being used: $LOOPDEV"

exit_hdl() {
	losetup -d "$LOOPDEV" || echo "[!] Failed to detach the loop device."
	rm -f "$TESTIMG" || echo "[!] Failed to remove the test image."
}

trap "exit_hdl" ERR EXIT SIGINT

read_uuid() {
	local _res
	_res="$(blkid --probe --output value --match-tag UUID "$1")"
	printf -- "%s" "$_res"
}

ROUNDS="$1"
losetup -Pv "$LOOPDEV" "$TESTIMG"

for i in `seq 1 $(( ROUNDS ))` ; do
	echo "[+] [$i/$ROUNDS] Repartitoining ..."
	echo "$SCRIPT" | sfdisk -w always -q "$LOOPDEV"
	echo "[+] [$i/$ROUNDS] Running partprobe ..."
	partprobe "$LOOPDEV"
	echo "[+] [$i/$ROUNDS] Formatting filesystems ..."
	mkfs.vfat "$LOOPDEV"p1
	mkfs.ext4 -qF "$LOOPDEV"p2

	uuid_p1="$(read_uuid "$LOOPDEV"p1)"
	uuid_p2="$(read_uuid "$LOOPDEV"p2)"

	echo "[+] [$i/$ROUNDS] Filesystem UUID of the EFI partition : $uuid_p1"
	echo "[+] [$i/$ROUNDS] Filesystem UUID of the main partition: $uuid_p2"
	echo "[+] [$i/$ROUNDS] Waiting for 5 seconds ..."
	sleep 5
	echo "[+] Running tests ..."
	content="$(ls -l "/dev/disk/by-uuid/")"
	if [ ! -e /dev/disk/by-uuid/"$uuid_p1" ] || \
		[ ! -e /dev/disk/by-uuid/"$uuid_p2" ] ; then
		echo "[!] [$i/$ROUNDS] udev didn't properly update /dev/disk within 5 seconds."
		echo "[+] [$i/$ROUNDS] Content of 'ls -l' at the time of the test:"
		echo "$content"
		err=1
	fi
	echo "[+] [$i/$ROUNDS] Checking for duplicate entries ..."
	entries1=("$(find /dev/disk/by-uuid -type l -lname '*'"$LOOPDEV"'p1')")
	entries2=("$(find /dev/disk/by-uuid -type l -lname '*'"$LOOPDEV"'p2')")
	if [ "${#entries1[@]}" -gt 1 ] || [ "${#entries2[@]}" -gt 1 ] ; then
		echo "[!] /dev/disk/by-uuid has duplicate entries that points to the same block device."
		for f in "${entries1[@]}" ; do
			echo "$f -> ${LOOPDEV##*/}p1"
		done
		for f in "${entries2[@]}" ; do
			echo "$f -> ${LOOPDEV##*/}p2"
		done
		echo "[+] By the time you 'ls' this directory they probably will disappear."
		err=1
	fi
	if [ "$err" = "1" ] ; then
		echo "[!] Error(s) detected! Test failed."
		exit 1
	fi
done

echo "[+] Test passed."
exit 0
