#!/bin/bash

MD5SUMS=/tmp/md5sums.txt
ARCHIVE=/tmp/archive.fsa
MNT=$(mktemp -d)
FILE=/tmp/loop

#
# Cleanup
#
finish() {
	echo "Cleaning up..."
	mountpoint -q $MNT && umount $MNT
	losetup -d $DEVICE
	rm -f $ARCHIVE
	rm -f $FILE
	rm -f $MD5SUMS
	rmdir $MNT
}
trap finish EXIT

#
# Execute test suite
#
run() {
	# Create a 300M file backing our file system
	dd if=/dev/zero of=$FILE bs=1M count=300 status=none

	DEVICE=$(losetup -fP --show $FILE)
	echo "*** Successfully created $DEVICE"

	# Create a test file system
	LABEL=Test
	UUID=$(cat /proc/sys/kernel/random/uuid)
	create_fs $LABEL $UUID $DEVICE


	echo "*** Mounting test file system at $MNT"
	mount $DEVICE $MNT

	# Generate some "random data"
	mkdir $MNT/test
	for i in $(seq 1 50) ; do
		dd if=/dev/urandom of=$MNT/test/$i bs=1M count=1 status=none
	done
	md5sum $MNT/test/* > $MD5SUMS

	umount $MNT


	# Backup
	fsarchiver savefs $ARCHIVE $DEVICE

	# Accidentally delete the data
	mount $DEVICE $MNT
	rm $MNT/test/*
	umount $MNT

	# Restore
	# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1142652 suggests to use wipefs for btrfs if a UUID is re-used
	if [ "$(lsblk -n -o FSTYPE $DEVICE)" = "btrfs" ]; then
		wipefs -a $DEVICE
	fi
	echo "*** Restoring backup..."
	fsarchiver restfs -ddd $ARCHIVE id=0,dest=$DEVICE || (
		echo "*** FSArchiver log"
		cat /var/log/fsarchiver*.log ;
		echo "*** kernel log"
		dmesg --since "1 min ago" ;
		exit 1
	)

	# Mount and compare data
	mount $DEVICE $MNT
	md5sum -c --quiet $MD5SUMS

	echo "*** Data successfully restored"

	# Test if LABEL and UUID were correctly restored
	LABEL_RESTORED=$(get_restored_label $DEVICE)
	UUID_RESTORED=$(get_restored_uuid $DEVICE)

	if [ "$LABEL" != "$LABEL_RESTORED" ]; then
		echo "Expected LABEL $LABEL, got $LABEL_RESTORED"
		exit 1
	fi
	if [ "$UUID" != "$UUID_RESTORED" ] ; then
		echo "Expected UUID $UUID, got $UUID_RESTORED"
		exit 1
	fi

	echo "*** LABEL and UUID successfully restored"

}