#!/bin/bash
today=$(date +%F)

# added trying to be clever
yesterday=$(date --date yesterday +%F)

echo "Fixing permissions..."
chgrp -R 2000 /current
echo "Cleaning up..."
rm -rf /scratch/*
echo "Downloading bundles from Google Cloud Storage..."
output=$(gsutil cp -R gs://backups.code.secondbit.org/$today/\* /scratch 2>&1)
echo $output

bundles=$(find /scratch -name '*.bundle')

# added trying to be clever
# basically, if we get an error downloading the bundles, try for yesterday's
# this could happen if the pod restarts between the last upload of day A and the first upload of day B
if [ $output == *"No URLs matched:"* ]
	echo "Downloading yesterday's bundles from Google Cloud Storage..."
	gsutil cp -R gs://backups.code.secondbit.org/$yesterday/\* /scratch
	mv /scratch/$yesterday /scratch/$today
	bundles=$(find /scratch -name '*.bundle' | wc -l)
fi

for bundle in $bundles
do
	dir=$(dirname $bundle)
	echo "dir=$dir"
	stripped=${dir#.}
	echo "stripped=$stripped"
	stripped=${stripped#/scratch}
	echo "stripped=$stripped"
	target=${bundle#/scratch}
	echo "target=$target"
	target=${target%.bundle}
	echo "target=$target"
	if [ -d "/current${target}" ]
	then
		echo "Pulling changes from $bundle to /current$target"
		hg --cwd /current${target} pull $bundle
	else
		echo "Creating /current$target repo from $bundle"
		hg clone $bundle /current${target}
		chgrp -R 2000 /current${target}
	fi
done
echo "Cleaning up..."
rm -rf /scratch/*

repos=$(find /current -name .hg -type d)
for repo in $repos
do
	dir=$(dirname $repo)
	echo "dir=$dir"
	stripped=${dir#.}
	echo "stripped=$stripped"
	stripped=${stripped#/current}
	echo "stripped=$stripped"
	target=/scratch/$today$stripped.bundle
	echo "target=$target"
	mkdir -p $(dirname $target)
	echo "Bundling $dir to $target"
	hg --cwd $dir bundle --all $target
done
echo "Pushing bundles to Google Cloud Storage..."
gsutil cp -R /scratch/* gs://backups.code.secondbit.org/
echo "Cleaning up..."
rm -rf /scratch/*
# sleep between 5 and 10 minutes
# randomized to prevent all our servers running this at the same time
sleepfor="$[($RANDOM % 5) + 5]m"
echo "Sleeping for $sleepfor..."
sleep $sleepfor
