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

yesterday=$(date --date yesterday +%F)

DOMAIN=${DOMAIN:-code.secondbit.org}
BACKUP_BUCKET=${BACKUP_BUCKET:-backups.$DOMAIN}

echo "Fixing permissions..."
chgrp -R 2000 /mounted/repos

echo "Cleaning up..."
rm -rf /tmp/repos/*

echo "Downloading bundles from gs://${BACKUP_BUCKET}/${today}"

output=$(gsutil cp -R gs://$BACKUP_BUCKET/$today/\* /tmp/repos 2>&1)
echo $output

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

# 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:"* ]]
then
	echo "Downloading yesterday's bundles from gs://${BACKUP_BUCKET}/${yesterday}"
	gsutil cp -R gs://$BACKUP_BUCKET/$yesterday/\* /tmp/repos
	mv /tmp/repos/$yesterday /tmp/repos/$today
	bundles=$(find /tmp/repos -name '*.bundle')
fi

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

echo "Cleaning up..."
rm -rf /tmp/repos/*

echo "Pull complete."
