#!/usr/bin/env bash

if tty -s
then
	set -x
fi

echo Starting backup at "`date`"

PATH=/usr/local/bin:$PATH

SRCDIR=/home
remotehost=root@sand.ess.uci.edu
DESTDIR=/data

if ssh "$remotehost" "cd /$DESTDIR/backups"
then
	:
else
	echo "Error cd'ing to top-level backup directory on $remotehost" 1>&2
	exit 1
fi

if ssh "$remotehost" "cd /$DESTDIR/backups && mkdir -p daily.1 daily.2 weekly.1 weekly.2 monthly.1 monthly.2"
then
	:
else
	echo Error creating backup directories on $remotehost 1>&2
	exit 1
fi

day_of_month="`date +%d`"
day_of_week="`date +%a`"

if ssh "$remotehost" "cd /$DESTDIR/backups && rm -rf daily.2 && mv daily.1 daily.2"
then
	:
else
	echo "Error rm'ing daily.1 or mv'ing daily.2 on $remotehost" 1>&2
	exit 1
fi

if ssh "$remotehost" "cd /$DESTDIR/backups && mkdir -p daily.1"
then
	:
else
	echo "Error cd\'ing to daily.1 $remotehost" 1>&2
	exit 1
fi

	
if tty -s
then
	# interactive version gives an estimated time of completion, &c
	approxsizeinkbytes="$(du -sk $SRCDIR | awk ' { print $1 }')"
	# reblock before gzip will be a little bit slower, but will also give
	# much better estimates.
	if (cd "$SRCDIR" && gtar cf - .) | \
		reblock -e "$approxsizeinkbytes" $(expr 1024 \* 1024) 300 | \
		gzip | \
		ssh "$remotehost" "umask 077 && cat > $DESTDIR/backups/daily.1/archive.tar.gz"
	then
		echo "Tar\'ed up without error" 1>&2
	else
		echo "Error tar\'ing $SRCDIR to $remotehost:/$DESTDIR" 1>&2
		exit 1
	fi
else	
	# batch version just goes the job relatively silently
	if (cd "$SRCDIR" && gtar cf - .) | gzip | ssh "$remotehost" "umask 077 && cat > $DESTDIR/backups/daily.1/archive.tar.gz"
	then
		echo "Tar\'ed up without error" 1>&2
	else
		echo "Error tar\'ing $SRCDIR to $remotehost:/$DESTDIR" 1>&2
		exit 1
	fi
fi

if ssh "$remotehost" "umask 077 && tar tvzf $DESTDIR/backups/daily.1/archive.tar.gz > $DESTDIR/backups/daily.1/tvf"
then
	echo "Generated table of contents without error" 1>&2
else
	echo "Error generating table of contents file on $remotehost" 1>&2
	exit 1
fi

if [ "$day_of_week" = Sun ]
then
	if ssh "$remotehost" "cd /$DESTDIR/backups && rm -rf weekly.2 && mv weekly.1 weekly.2 && mkdir weekly.1 && cp daily.1/* weekly.1/."
	then
		echo "Rotated weekly" 1>&2
	else
		echo "Error rotating weekly" 1>&2
	fi
fi

if [ "$day_of_month" = 01 ]
then
	if ssh "$remotehost" "cd /$DESTDIR/backups && rm -rf monthly.2 && mv monthly.1 monthly.2 && mkdir monthly.1 && cp daily.1/* monthly.1/."
	then
		echo "Rotated monthly" 1>&2
	else
		echo "Error rotating monthly" 1>&2
	fi
fi

echo Backup finished at "`date`"