#!/bin/bash
#Copyright 2001-2003, William Stearns
#Released under the GPL.

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

if [ ! -d /backups ]; then
	if type -path logger >/dev/null 2>/dev/null ; then
		logger -t rsync-backup-weekly-maintenance No /backups directory, so no weekly 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
if ! type -path cd >/dev/null 2>/dev/null ; then	debug No cd ;		exit 1 ; fi
if ! type -path date >/dev/null 2>/dev/null ; then	debug No date ;		exit 1 ; fi

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

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

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

if ! type -path rm >/dev/null 2>/dev/null ; then	debug No rm ;		exit 1 ; fi
rm -f /backups/*/current/rsync-static

cd /backups
if ! type -path freedups >/dev/null 2>/dev/null ; then	debug No freedups ;	exit 1 ; fi

if type -path date >/dev/null 2>/dev/null && type -path df >/dev/null 2>/dev/null; then
	debug Before Freedups `date`
	debug "`df /backups`"
fi

if type -path nice >/dev/null 2>/dev/null ; then
	Nice="nice "
else
	Nice=" "
fi
#Old approach, but freedups can't process this many files.  :-(
#$Nice freedups -a -d . >/dev/null 2>/dev/null

cd /backups
for ONESUB in bin boot dev etc home initrd lib misc mnt opt root sbin tmp usr var ; do
	DIRS=''
	for ONEIP in * ; do
		if [ -d "$ONEIP" ] && [ ! -L "$ONEIP" ] && [ -d "/backups/$ONEIP/current/$ONESUB" ]; then
			DIRS="$DIRS /backups/$ONEIP/current/$ONESUB"
		fi
	done
	if [ -n "$DIRS" ]; then
		debug "Freeing duplicates in allbackups/current/$ONESUB"
		$Nice freedups -a -d $DIRS >/dev/null 2>/dev/null
	fi
done

cd /backups
for ONEDIR in * ; do
	if [ -d "/backups/$ONEDIR" ] && [ ! -L "/backups/$ONEDIR" ] && [ -d "/backups/$ONEDIR/current" ]; then
		cd "/backups/$ONEDIR"
		debug "Freeeing duplicates for system $ONEDIR"
		for ONESNAP in [0-9]* ; do
			if [ -d "/backups/$ONEDIR/$ONESNAP" ] && [ ! -L "/backups/$ONEDIR/$ONESNAP" ]; then
				debug "Snapshot $ONESNAP"
				$Nice freedupsA -a -d "/backups/$ONEDIR/current/" "/backups/$ONEDIR/$ONESNAP/" >/dev/null 2>/dev/null
			fi
		done
	fi
done

if type -path date >/dev/null 2>/dev/null && type -path df >/dev/null 2>/dev/null; then
	debug After Freedups `date`
	debug "`df /backups`"
fi

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

