#!/bin/bash

# Write a 4096 byte block of something
block ()
{
	head -c 4096 /dev/zero | tr '\0' "\\$1";
}

# Here is some test data with holes in it:
for y in $(seq 0 2); do
	for x in 0 1; do
		block 0;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
		block 21;
	done
done > am
sync

echo "file size: $(du -h am)"

echo "digests after file creation:   $(sha1sum am)"
sysctl -q vm.drop_caches=1
echo "digests after file creation 2: $(sha1sum am)"

# Now replace those 101 distinct extents with 101 references to the first extent
btrfs-extent-same 131072 $(for x in $(seq 0 2); do echo am $((x * 131072)); done) 2>&1 | tail -1

echo "digests after dedupe:          $(sha1sum am)"
sysctl -q vm.drop_caches=1
echo "digests after dedupe 2:        $(sha1sum am)"

# Punch holes into the extent refs
fallocate -v -d am

echo "digests after hole punching:   $(sha1sum am)"
sysctl -q vm.drop_caches=1
echo "digests after hole punching 2: $(sha1sum am)"