#!/bin/bash

SOURCE_DIR=/home;
SNAPSHOTS_DIR=/mnt/external/vips-backup;
MAX_NUMBER_OF_OLD_SNAPSHOTS=100;  

# Check that the directory for the snapshots is a directory we can write to
if [ ! -d $SNAPSHOTS_DIR ] ; then
    echo The directory $SNAPSHOTS_DIR does not exists.  Trying to create it:
    mkdir $SNAPSHOTS_DIR ;
fi

# Check that the source directory exists, just for good meassure
if [ ! -d $SOURCE_DIR ] ; then
    echo The source directory $SOURCE_DIR does not exists, Bye, bye...
    exit ;
fi

# Delete the oldest snapshot if it exists
if [ -d $SNAPSHOTS_DIR/snapshot.$MAX_NUMBER_OF_OLD_SNAPSHOTS ] ; then
    echo Deleting the oldest snapshot.  Is that OK? 
    read -p "[Yn] "
    if [ -z $REPLY ] || [ $REPLY != n ] ; then 
        rm -rf $SNAPSHOTS_DIR/snapshot.$MAX_NUMBER_OF_OLD_SNAPSHOTS
    fi
fi

# Roll the the existing snapshots 
for i in `seq $MAX_NUMBER_OF_OLD_SNAPSHOTS -1 0`; do
    newi=$(($i+1)) ;
    if [ -d $SNAPSHOTS_DIR/snapshot.$i ] ; then
        mv $SNAPSHOTS_DIR/snapshot.$i $SNAPSHOTS_DIR/snapshot.$newi ;
    fi
done

# Do the rsync magic
echo Starting the rsync\'ing
rsync -a --delete --stats --times \
      --link-dest=$SNAPSHOTS_DIR/snapshot.1 \
      $SOURCE_DIR $SNAPSHOTS_DIR/snapshot.0


