#!/bin/bash
#
# This script will redirect the backup directory to implement desired backup
# schedules.
#
# Currently we will use just a seven day format were we just move a link
# that represents the backup directory, to point to the day of the week.
#

#
# Configuration Parameters
#

if [ "$1" = "monthly" ]; then
   REALDIR="monthly"
else
   REALDIR=`date +%A`
fi

BACKUPPART="/backup"
BACKUPDIR="current"

echo "### Start of Backup Rotation ###"
echo "Using backup partition: $BACKUPPART"

echo -n "Remounting backup partition read-write ... "
if ( mount $BACKUPPART -o remount,rw &> /dev/null ) then
   echo "done."
else
   echo "failure!"
   echo "   There were problems remounting $BACKUPPART in read-write mode!"
   echo "Rotation not made!"
   echo "### End of Backup Rotation ###"
   exit 1
fi

echo -n "Checking that no directory named \"$BACKUPDIR\" exists ... "
if [ -d $BACKUPPART/$BACKUPDIR -a ! -L $BACKUPPART/$BACKUPDIR ]; then
   echo "failure!"
   echo "   Directory \"$BACKUPDIR\" exists. Can't create link!"
   echo "Rotation not made!"

   echo -n "Remounting backup partition read-only ... "
   if ( mount $BACKUPPART -o remount,ro &> /dev/null ) then
      echo "done."
   else
      echo "failure!"
      echo "   There were problems remounting $BACKUPPART in read-only mode!"
      echo "### End of Backup Rotation ###"
      exit 1
   fi
   echo "### End of Backup Rotation ###"
   exit 1
else
   echo "done."
fi

cd $BACKUPPART

echo -n "Creating link: $BACKUPDIR --> $REALDIR ... "
if ( ln -snf $REALDIR $BACKUPDIR &> /dev/null ) then
   echo "done."
else
   echo "failure!"
   echo "   There were problems creating link!"
   echo "Rotation not made!"

   echo -n "Remounting backup partition read-only ... "
   if ( mount $BACKUPPART -o remount,ro &> /dev/null ) then
      echo "done."
   else
      echo "failure!"
      echo "   There were problems remounting $BACKUPPART in read-only mode!"
      echo "### End of Backup Rotation ###"
      exit 1
   fi 
   echo "### End of Backup Rotation ###"
   exit 1
fi

echo -n "Remounting backup partition read-only ... "
if ( mount $BACKUPPART -o remount,ro &> /dev/null ) then
   echo "done."
else
   echo "failure!"
   echo "   There were problems remounting $BACKUPPART in read-only mode!"
   echo "### End of Backup Rotation ###"
   exit 1
fi
echo "### End of Backup Rotation ###"
