#!/bin/sh

# ClonePanel - Manages duplicate accounts on two or more webservers,
# including snapshot backups, monitoring and failover dns.
# Copyright (C)2006 Chris Cheers, Internet Lynx.
# Contact chris[at]clonepanel[dot]com.
# Internet Lynx, PO Box 7117, Mannering Park, NSW 2259, Australia

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

Version=0.33
# rollover -h for built-in documentation

set -u
# Be strict about variable declaration

unset PATH
#avoid use of $PATH - limit script to system commands we choose

PROGRAM_DIR=$(/bin/echo $0 |/bin/sed -e "s/\/[a-zA-Z0-9_]*$//")
# Extract the working directory from command line
# NB - if your system doesn't have echo and sed in these locations
# then this line will need to be changed in all shell scripts

# Standard include files:
. $PROGRAM_DIR/includes

# Built-in documentation:
function showdocs {
	$CAT <<-EODOC
		rollover must be given an account name
		It checks the last run date and runs daily / weekly / monthly rollovers, ie
		it rolls back the daily snapshots and moves the oldest hourly snapshot
		into the line, and likewise for weekly / monthly.
	
		Command line options: 
		-h	Print these instructions and exit
		-u user	username of the account
		-d 7	(optional) number of daily snapshots to keep
		-w 4	(optional) number of weekly snapshots to keep
		-m 6	(optional) number of monthly snapshots to keep

EODOC
	exit $DOC_REQUEST
}


# Initialise own input variables and defaults
user=''
daily=$DAILY_SNAPSHOTS
weekly=$WEEKLY_SNAPSHOTS
monthly=$MONTHLY_SNAPSHOTS


# Start real script

# Check for help request and input variables in the command line options:
while getopts ":hu:d:w:m:" opt
do
	case $opt in
		h)	showdocs
			;;
		u)	user=$OPTARG
			;;
		d)	daily=$OPTARG
			;;
		w)	weekly=$OPTARG
			;;
		m)	monthly=$OPTARG
			;;
		*)	$ECHO "Unknown option. Use -h for instructions"; exit $E_UNKNOWN_OPT
			;;
	esac
done
shift $(($OPTIND - 1))
OPTIND=1
# reset getopts for next time


if [ ! $user ]; then
	cecho -c $error "Username must be specified"
	exit $E_BLANK_INPUTS
fi

# User-specific Include files (only after defining $user):
config -u $user

function rollem {
# Do the real work of rolling snapshots here
	period=$1
	stype=$2
	cecho -c $info "Rotating $period $stype snapshots"
	
	case "$period" in
			daily)
				period_snaps=$daily
				shorter=hourly
				shorter_snaps=$NO_SNAPSHOTS
	# define variables for transfer from hourly to daily			
				;;
			weekly)
				period_snaps=$weekly
				shorter=daily
				shorter_snaps=$daily
	# define variables for transfer from daily to weekly
				;;
			monthly)
				period_snaps=$monthly
				shorter=weekly
				shorter_snaps=$weekly ;
	# define variables for transfer from weekly to monthly			
				;;
			*)
				cecho -c $error "Unknown period"
				exit $E_UNKNOWN_PERIOD
				;;
	esac

	# NB - comments below assume rolling daily snapshots, same logic applies for longer periods
	# does the oldest hourly snapshot exist?:
	if [ -d $SNAPSHOT_DIR/$stype/$shorter.$shorter_snaps ] ; then
	# if so, remove the oldest daily, if that exists
		if [ -d $SNAPSHOT_DIR/$stype/$period.$period_snaps ] ; then
			$RM -rf $SNAPSHOT_DIR/$stype/$period.$period_snaps ;
		fi ;
	# then shift the daily snapshots back by one, if they exist
		for (( i=$period_snaps; i > 0; i-- ))
		do
			j=$($EXPR $i - 1) ;
			if [ -d $SNAPSHOT_DIR/$stype/$period.$j ] ; then
				$MV $SNAPSHOT_DIR/$stype/$period.$j $SNAPSHOT_DIR/$stype/$period.$i ;
			fi;
		done ;
	# and finally change the oldest hourly snapshot into the newest daily
		$MV $SNAPSHOT_DIR/$stype/$shorter.$shorter_snaps $SNAPSHOT_DIR/$stype/$period.0 ;
	fi ;
}

weekday=$($DATE +%a)
month=$($DATE +%b)
day=$($DATE +%d)


for dir in `$FIND $SNAPSHOT_DIR -maxdepth 1 -type d -printf "%f "`
do
	if [ "$day" == "$ROLLMONTHDAY" ]; then
		rollem "monthly" "$dir"
	fi
	if [ "$weekday" == "$ROLLWEEKDAY" ]; then
		rollem "weekly" "$dir"
	fi
	rollem "daily" "$dir"
	# always run daily roll (cron this once per day)
done

cecho -c $ok "Rollover complete"
