#!/usr/bin/env bash

set -eux

rm -rf save-dir-*

record=$(../../this-interpreter --variety fast)
pyver=$(echo "$record" | awk -F'%' ' { print $1 }')
python=$(echo "$record" | awk -F'%' ' { print $2 }')

mkdir -p save-dir-"$pyver"

slow_output=$(set -eu; set -o pipefail > /dev/null 2>&1 || true; find to-be-saved -name .svn -prune -o -print0 | \
	"$python" ../../bin/backshift \
		--save-directory save-dir-"$pyver" \
		--backup \
		--hostname $(hostname) \
		--subset test \
		--init-savedir)

fast_output=$(set -eu; set -o pipefail > /dev/null 2>&1 || true; find to-be-saved -name .svn -prune -o -print0 | \
	"$python" ../../bin/backshift \
		--save-directory save-dir-"$pyver" \
		--backup \
		--hostname $(hostname) \
		--subset test \
		--init-savedir)

if [ $(echo "$slow_output" | egrep -c perc100) -ge 4 ]
then
	:
else
	echo "$0: slow count bad" 1>&2
	echo "$slow_output"
	exit 1
fi

if [ $(echo "$fast_output" | egrep -c mtime) -ge 4 ]
then
	:
else
	echo "$0: fast count bad" 1>&2
	echo "$fast_output"
	exit 1
fi

backup_id=$(set -eu; "$python" ../../bin/backshift --save-directory save-dir-"$pyver" --list-backups | \
	tail -1 | \
	sed 's/ .*$//')

rm -rf restore-dir-"$pyver"
mkdir -p restore-dir-"$pyver"

"$python" ../../bin/backshift \
	--save-directory save-dir-"$pyver" \
	--produce-tar \
	--backup-id $backup_id | \
	(cd restore-dir-"$pyver" && tar xvf -)

(tbs=$(pwd); cd restore-dir-""$pyver"" && mv ./"$tbs"/to-be-saved . && echo rm -rf ./$(dirname "$tbs"))

(find ./to-be-saved -name .svn -prune -o -type f -print0 | xargs -0 md5sum -b | sort -k 2) > to-be-saved.md5sums
(cd restore-dir-"$pyver" && find . -type f -print0 | xargs -0 md5sum -b | sort -k 2) > restore-dir-"$pyver".md5sums

echo Diffing "$pyver"
diff -C8 -b to-be-saved.md5sums restore-dir-"$pyver".md5sums