#! /bin/bash

set -e

restore()
{
	echo "------Restore base snapshot---------"
	echo "Delete last snap, if any"
	./btrfs sub del /mnt/src/snap1 || true
	echo "Delete cg0"
	./btrfs sub del /mnt/src/cg0
	echo "Re-create cg0 from snap0"
	./btrfs sub snap /mnt/src/snap0 /mnt/src/cg0
	tree -A  --inodes --noreport /mnt/src/cg1
	echo "------Base snapshot restored---------"
}

do_diff_send()
{
	echo "Delete snap1 if any"
	./btrfs sub del /mnt/src/snap1 || true
	echo "Create snap1 from cg0"
	./btrfs sub snap -r /mnt/src/cg0 /mnt/src/snap1
	echo "send snap1"
	./btrfs send -v -v -v -v -p /mnt/src/snap0 /mnt/src/snap1 > /tmp/dump
	echo "Print prev and curr trees"
	tree -A  --inodes --noreport /mnt/src/snap0
	tree -A  --inodes --noreport /mnt/src/snap1
	
	echo "Delete snap1 if any on dest"
	./btrfs sub del /mnt/dst/snap1 || true
	echo "Receive"
	./btrfs receive -v -v -v /mnt/dst/  < /tmp/dump
	echo "Validate"
	diff -r /mnt/src/snap1 /mnt/dst/snap1
	echo "Success!"
}

do_full_send()
{
	echo "Delete snap1 if any"
	./btrfs sub del /mnt/src/snap1 || true
	echo "Create snap1 from cg0"
	./btrfs sub snap -r /mnt/src/cg0 /mnt/src/snap1
	echo "send snap1 fully"
	./btrfs send -v -v -v -v /mnt/src/snap1 > /tmp/dump
	echo "Print full tree"
	tree -A  --inodes --noreport /mnt/src/snap1

	echo "Delete snap1 if any on dest"
	./btrfs sub del /mnt/dst/snap1 || true
	echo "Receive"
	./btrfs receive -v -v -v /mnt/dst/  < /tmp/dump
	echo "Validate"
	diff -r /mnt/src/snap1 /mnt/dst/snap1
	echo "Success!"
}


test1()
{
echo "#####################################"
echo  "Add HL to existing file, which overwrites 'second' HL of another existing file"
restore
unlink /mnt/src/cg0/dir2/dir3/file1_dir1
ln /mnt/src/cg0/file1_nod /mnt/src/cg0/dir2/dir3/file1_dir1
do_diff_send
echo  "Test done."
}

test11()
{
echo "#####################################"
echo  "Add HL to existing file, which overwrites 'first' HL of another existing file"
restore
unlink /mnt/src/cg0/dir1/file1_dir1
ln /mnt/src/cg0/file1_nod /mnt/src/cg0/dir1/file1_dir1
do_diff_send
echo  "Test done."
}

test111()
{
echo "#####################################"
echo  "Add HL to existing file, which overwrites 'second' HL of another existing file, but the existing file is lower ino"
restore
unlink /mnt/src/cg0/dir2/dir3/file1_dir1
ln /mnt/src/cg0/dir2/dir3/file3_dir3 /mnt/src/cg0/dir2/dir3/file1_dir1
do_diff_send
echo  "Test done."
}

test112()
{
echo "#####################################"
echo  "Add HL to existing file, which overwrites 'first' HL of another existing file, but the existing file is lower ino"
restore
unlink /mnt/src/cg0/dir1/file1_dir1
ln /mnt/src/cg0/dir2/dir3/file3_dir3 /mnt/src/cg0/dir1/file1_dir1
do_diff_send
echo  "Test done."
}

test112
