root="$(pwd)"
disks="disk1.img disk2.img disk3.img"
imgsize=500M


#
# returns all the loopback devices
#
loop_disks() {
	sudo losetup | grep $root | awk '{ print $1 }'
}


#init the fs

init_fs() {
	#destroy fs
	echo umount mnt
	sudo umount mnt
	for i in $( loop_disks ); do
		echo "losetup -d $i"
		sudo losetup -d $i
	done

	for i in $disks; do
		rm $i
		truncate -s $imgsize $i
		sudo losetup -f $i
	done

	loops="$(loop_disks)"
	loop1="$(echo $loops | awk '{ print $1 }')"
	echo "loops=$loops; loop1=$loop1"

	sudo mkfs.btrfs -d raid5 -m raid5 $loops
	sudo mount $loop1 mnt/

	python -c "print 'ad'+'a'*65534+'bd'+'b'*65533" | sudo tee mnt/out.txt >/dev/null

	ls -l mnt/out.txt

	sudo umount mnt
	sync; sync
}

check_fs() {
	# check
	d="$(dd 2>/dev/null if=/dev/loop0 bs=1 skip=$((81788928+16*4096)) count=5)"
	if [ "$d" != "bdbbb" ]; then
		echo "******** Wrong data on disk /dev/loop0 [$d]"
		return 1
	fi

	d="$(dd 2>/dev/null if=/dev/loop1 bs=1 skip=$((61865984+16*4096)) count=5)"
	if [ "$d" != "adaaa" ]; then
		echo "******** Wrong data on disk /dev/loop1 [$d]"
		return 1
	fi
	d="$(dd 2>/dev/null if=/dev/loop2 bs=1 skip=$((61865984+16*4096)) count=5 | xxd | dd bs=1 count=4 skip=10)"
	if [ "x$d" != "x0300" ]; then
		echo "******* Wrong data on disk /dev/loop2 [$(echo -n $d)]"
		return 1
	fi

	return 0
}

test_corrupt_loop2() {
	echo "--- test 1: corrupt loop2"
	echo 3 | sudo tee /proc/sys/vm/drop_caches
	sudo dd if=/dev/zero of=/dev/loop2 bs=1 \
		seek=$((61865984+16*4096)) count=5
	check_fs &>/dev/null && {
			echo Corruption failed
			exit 100
		}
	echo 3 | sudo tee /proc/sys/vm/drop_caches
	sudo mount /dev/loop0 mnt
	sudo btrfs scrub start mnt/.
	sync; sync
	cat mnt/out.txt &>/dev/null || echo "Read FAIL"
	sudo umount mnt
	check_fs || exit
	echo "--- test1: OK"
}



test_corrupt_loop1() {
	echo "--- test 2: corrupt loop1"
	echo 3 | sudo tee /proc/sys/vm/drop_caches
	sudo dd if=/dev/zero of=/dev/loop1 bs=1 \
		seek=$((61865984+16*4096)) count=5
	check_fs &>/dev/null && {
			echo Corruption failed
			exit 100
		}
	echo 3 | sudo tee /proc/sys/vm/drop_caches
	sudo mount /dev/loop0 mnt
	sudo btrfs scrub start mnt/.
	sync; sync
	cat mnt/out.txt &>/dev/null || echo "Read FAIL"
	sudo umount mnt
	check_fs || exit
	echo "--- test2: OK"
}

test_corrupt_loop0() {
	echo "--- test 3: corrupt loop0"
	echo 3 | sudo tee /proc/sys/vm/drop_caches
	sudo dd if=/dev/zero of=/dev/loop0 bs=1 \
		seek=$((81788928+16*4096)) count=5
	check_fs &>/dev/null && {
			echo Corruption failed
			exit 100
		}
	echo 3 | sudo tee /proc/sys/vm/drop_caches
	sudo mount /dev/loop0 mnt
	sudo btrfs scrub start mnt/.
	sync; sync
	cat mnt/out.txt &>/dev/null || echo "Read FAIL"
	sudo umount mnt
	check_fs || exit
	echo "--- testr3: OK"
}


init_fs
check_fs || exit 100
echo "Integrity test OK"

test_corrupt_loop0



