#! /bin/bash

set -e

echo "Cleanup...."
./btrfs sub del /mnt/src/cg0 || true
./btrfs sub del /mnt/src/snap_cg0_orig/ || true
./btrfs sub del /mnt/src/snap0/ || true
./btrfs sub del /mnt/dst/snap0/ || true
./btrfs sub del /mnt/dst/snap1/ || true

echo "Create base subvolume and fill with data..."
./btrfs sub create /mnt/src/cg0
mkdir /mnt/src/cg0/dir1
dd if=/dev/urandom of=/mnt/src/cg0/file1_nod bs=1 count=163
dd if=/dev/urandom of=/mnt/src/cg0/file2_nod bs=1 count=9515 seek=140000
dd if=/dev/urandom of=/mnt/src/cg0/dir1/file2_dir1 bs=1 count=20000 seek=10000
dd if=/dev/urandom of=/mnt/src/cg0/dir1/file1_dir1 bs=1 count=72063
cp /mnt/src/cg0/dir1/file2_dir1 /mnt/src/cg0/dir1/file3_dir1_trunc
dd if=/dev/urandom of=/mnt/src/cg0/dir1/file3_dir1_trunc bs=1 seek=69999 count=1 conv=notrunc
touch /mnt/src/cg0/file2_nod
touch /mnt/src/cg0/file3_nod
touch /mnt/src/cg0/dir1/file4_dir1
mkdir /mnt/src/cg0/dir2
ln /mnt/src/cg0/dir1/file1_dir1 /mnt/src/cg0/dir2/file1_dir1_HL
touch /mnt/src/cg0/dir2/file1_dir2
mkdir /mnt/src/cg0/dir2/dir3
touch /mnt/src/cg0/dir2/dir3/file1_dir3
touch /mnt/src/cg0/dir2/dir3/file2_dir3
touch /mnt/src/cg0/dir2/dir3/file3_dir3
ln /mnt/src/cg0/dir1/file1_dir1 /mnt/src/cg0/dir2/dir3/

echo "Creating backup snap..."
./btrfs sub snap -r /mnt/src/cg0 /mnt/src/snap_cg0_orig/

echo "Creating base snap for send ..."
./btrfs sub snap -r /mnt/src/cg0 /mnt/src/snap0
echo "Sending full tree..."
./btrfs send -v -v -v /mnt/src/snap0 > /tmp/dump
echo "Receiving..."
./btrfs receive /mnt/dst < /tmp/dump

echo "Checking diff -r"
diff -r /mnt/src/snap0 /mnt/dst/snap0 

echo "Done setting up test:"
tree -A  --inodes --noreport /mnt/src/cg0
