#!/bin/bash
today=$(date +%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/*

repos=$(find /mounted/repos -name .hg -type d)
for repo in $repos
do
	dir=$(dirname $repo)
	stripped=${dir#.}
	stripped=${stripped#/mounted/repos}
	target=/tmp/repos/$today$stripped.bundle
	mkdir -p $(dirname $target)
	hg --cwd $dir bundle --all $target
done

echo "Pushing bundles to gs://${BACKUP_BUCKET}"
gsutil cp -R /tmp/repos/* gs://${BACKUP_BUCKET}/

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

echo "Push complete."
