#!/bin/bash

set -e

MD5SUMS=/tmp/md5sums.txt
ARCHIVE=/tmp/archive.fsa
MNT=/mnt
FILE=/tmp/loop

# Create a 100M file
dd if=/dev/zero of=$FILE bs=1M count=500 status=none

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

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

# Create an XFS file system
LABEL=Test
UUID=$(uuidgen)
mkfs.xfs -q -L $LABEL -m uuid=$UUID $DEVICE

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
fsarchiver restfs $ARCHIVE id=0,dest=$DEVICE

# 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=$(xfs_admin -l $DEVICE | awk  '{print $3}' | tr -d \")
UUID_RESTORED=$(xfs_admin -u $DEVICE | awk  '{print $3}')

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"

