#!/bin/bash
#Copyright 2001-2003, William Stearns

#Designed to be run from cron; simply place in /etc/cron.daily on RH, mode 755.
#This should be run _AFTER_ all backups should have completed.  RH
#runs at 4:02AM.

if [ ! -d /backups ]; then
	if type -path logger >/dev/null 2>/dev/null ; then
		logger -t rsync-backup-daily-maintenance "No /backups directory, so no daily maintenance to do, exiting."
		exit 1
	fi
fi
#mkdir -p /backups	#OK, if you don't have mkdir, you have bigger problems than this script... :-)

debug () {
	echo "$*" >>/backups/rsync-backup-debug
}

#System sanity check
for OneUtil in cd cp date rm ; do
	if ! type -path $OneUtil >/dev/null 2>/dev/null ; then
		debug No $OneUtil
		exit 1
	fi
done

DATESTAMP=`date +%Y%m%d`

if type -path logger >/dev/null 2>/dev/null ; then
	logger -t rsync-backup-daily-maintenance "Starting daily maintenance for $DATESTAMP."
fi
debug Starting daily maintenance for $DATESTAMP.

if ! cd /backups ; then
	if type -path logger >/dev/null 2>/dev/null ; then
		logger -t rsync-backup-daily-maintenance "Cannot cd to /backups, exiting."
	fi
	exit 1
fi

#rm -f /backups/*/current/rsync-static	#delete one by one below so we can know who needs a snapshot

for ONEDIR in * ; do
	cd /backups
	if [ -d "./$ONEDIR/current" ]; then
		cd "/backups/$ONEDIR"
		if [ -e $DATESTAMP ]; then
			debug "$DATESTAMP already exists in $ONEDIR"
		else
			if [ -f current/rsync-static ]; then
				rm -f current/rsync-static
				cp -a --link current $DATESTAMP
			else
				debug "Not making snapshot of $ONEDIR, apparently no backup was made."
			fi
		fi
	fi
done

if type -path logger >/dev/null 2>/dev/null ; then
	logger -t rsync-backup-daily-maintenance "Finished daily maintenance for $DATESTAMP."
fi
debug Finished daily maintenance for $DATESTAMP.