#!/bin/sh

# Christian Daehn (c) 2007, www.3DH.de
#
# Free to use for private and commercial use, 
# as long as my copyright stays in the script.
#
# Last modified: 2007-06-27

# try to mount all mountpoints
mount -a

# directory to backup
# - This is the path to the directory you want to archive
BACKUPDIR=/mnt/ninja/mp3

# root directory to for backup stuff
ARCHIVEROOT=/var/backups/mp3

# excludes file - contains one wildcard pattern per line of files to exclude
#  - This is a rsync exclude file.
EXCLUDES=$ARCHIVEROOT/excludes.lst

# log file
LOGFILE=$ARCHIVEROOT/backup.log

# directory which holds our current datastore
CURRENT=current

# calc yesterdays date
Y=`date +'%Y'`
M=`date +'%m'`
D=`date +'%d'`
TODAY=$Y-$M-$D

if [ $M -eq 01 -o $M -eq 03 -o $M -eq 05 -o $M -eq 07 -o $M -eq 08 -o $M -eq 10 -o $M -eq 12 ] && [ $D -eq 01 ];then
	YESTERDAY=`expr $D + 30`
else
	if [ $M -eq 04 -o $M -eq 06 -o $M -eq 09 -o $M -eq 11 ] && [ $D -eq 01 ]; then
		YESTERDAY=`expr $D + 29`
	else
		if [ $M -eq 02 -a $D -eq 01 ]; then
			YESTERDAY=`expr $D + 27`
		else
			YESTERDAY=`expr $D - 1`
		fi
	fi
fi

if [ $YESTERDAY -lt 10 ]; then
  YESTERDAY="0"$YESTERDAY
fi

YESTERDAY=$Y-$M-$YESTERDAY

# directory which we save incremental changes to
INCREMENTDIR=$TODAY
DECREMENTDIR=$YESTERDAY

# options to pass to rsync
OPTIONS="--force --ignore-errors --delete --delete-excluded --exclude-from=$EXCLUDES --copy-unsafe-links --backup --backup-dir=$ARCHIVEROOT/$INCREMENTDIR/ --link-dest=$ARCHIVEROOT/$DECREMENTDIR/ -av"

# make sure our backup tree exists
mkdir -p $ARCHIVEROOT/$CURRENT

# some error handling and/or run our backup and accounting
echo "---- Starting Backup `date +%Y-%m-%d_%H:%M:%S` ----" >>$LOGFILE

# now the actual transfer
/mnt/HD_a2/fun_plug.d/bin/rsync $OPTIONS $BACKUPDIR $ARCHIVEROOT/$CURRENT >>$LOGFILE

echo "---- Finished Backup `date +%Y-%m-%d_%H:%M:%S` ----" >>$LOGFILE
echo "" >>$LOGFILE

