#!/bin/bash

# by Erik Jan "alphageek" Tromp

# loosely based upon concepts gleaned from
# http://www.mikerubel.org/computers/rsync_snapshots/
# (thanks mike!)


# concept: rotate backup directories on a daily & hourly basis
# we're going to retain 1 week's worth of daily backups & 1 day's worth
# of hourly backups (00:00 will be symlinked to today's daily to save even
# more space)

# note: though exactly 1 week's worth of daily backups are retained,
#	you can tailor the number of hourly backups retained by simply
#	controlling how often you call the script from cron.
#
#	ie: '0 * * * *		rotate-backups' == 24 sets, 1 hour apart
#	    '0 */6 * * *	rotate-backups' == 4 sets, 6 hours apart

# known to work with the following versions of utilities under linux. ymmv
# bash	- 2.05.0
# cp	- fileutils 4.1
# date	- sh-utils 2.0
# mkdir	- fileutils 4.1
# rm	- fileutils 4.1
# tr	- textutils 2.0


# where it all takes place
BACKUPDIR="/backup"

# names of backup sets separated by spaces
# (note: I name the sets based upon hostname, pick what works best for you)
BACKUPSET="hydrogen helium lithium beryllium boron carbon nitrogen oxygen"

# day of week (forced lowercase)
DOW="$(date +%A | tr [:upper:] [:lower:])"

# hour of day
HOD="$(date +%H):00"


cd $BACKUPDIR

# 2 possible cases: either it's 00:00 or it isn't. it's that simple
if [ "$HOD" = "00:00" ] ; then
  DESTSET="$DOW"
else
  DESTSET="$HOD"
fi

#+
# out with the old
#rm -rf .$DESTSET
#mkdir .$DESTSET

# in with the new
#for i in $BACKUPSET ; do
#  if [ -d $i ] ; then
#    cp -al $i .$DESTSET/$i
#  fi
#done
#-

mkdir .$DESTSET.new

for i in $BACKUPSET ; do
  # out with the old
  [ -d .$DESTSET/$i ] && rm -rf .$DESTSET/$i

  # in with the new
  if [ -d $i ] ; then
    mv $i .$DESTSET.new/$i
    cp -al .$DESTSET.new/$i $i
  fi
done

# clean out possible 'old' leftovers
rm -rf .$DESTSET
mv .$DESTSET.new .$DESTSET

# why make 2 identical sets?
if [ "$HOD" = "00:00" ] ; then
  rm -f .$HOD
  ln -s .$DOW .$HOD
fi

# eof
