#!/bin/bash

function usage
{
	(
		echo "Usage: $0 [--normal|--overwrite|--help]"
		echo
		echo "Normal mode will do a backup with rotation"
		echo
		echo "Overwrite mode will overwrite the last daily backup, without doing any rotation at all.  It's for redoing a backup when a previous"
		echo "one fails."
	) 1>&2
	exit "$1"
}

mode=unknown

while [ "$#" -ge 1 ]
do
	if [ x"$1" = x--normal ]
	then
		mode=normal
	elif [ x"$1" = x--overwrite ]
	then
		mode=overwrite
	elif [ x"$1" = -h ] || [ x"$1" = x--help ]
	then
		usage 0
	else
		usage 1
	fi
	shift
done

#set -x
set -u

case "$mode" in
	normal)
		echo OK, I will do a normal backup with rotation 1>&2
		;;
	overwrite)
		echo OK, I will overwrite the most recent backup, without any sort of rotation 1>&2
		;;
	unknown)
		echo Sorry, you must specify either --normal or --overwrite 1>&2
		usage 1
		;;
esac

DESTDIR=/media/usbdisk/Backup.local
#DESTDIR=/notthere/gfs045/backup
SRCDIR=/big

# disabled Wed Nov  3 09:54:46 PST 2004, because $DESTDIR exists,
# but is not mounted

# Mon Sep 12 10:23:13 PDT 2005: reenabled, now that we have 3511+QFS
#exit 1

umask 077

PATH=/usr/local/bin:$PATH

mkdir -p "$DESTDIR"/backups
cd "$DESTDIR"/backups || \
	   {
	   echo "$0: cd to" $DESTDIR failed | mailx -s 'ESMF backup trouble' dcs@hydra.acs.uci.edu
	   touch /tmp/Backup-failed
	   exit 1
	   }

mkdir -p daily.1
mkdir -p daily.2
mkdir -p weekly.1
mkdir -p weekly.2
mkdir -p monthly.1
mkdir -p monthly.2

day_of_month="`date +%d`"
day_of_week="`date +%a`"

if [ "$mode" = normal ]
then
	rm -rf daily.2
	mv daily.1 daily.2

	mkdir -p daily.1
fi

if tty -s
then
	ONTTY=1
else
	ONTTY=0
fi
export ONTTY

if [ "$ONTTY" = 1 ]
then
	blocks="$(du -sk $SRCDIR | awk ' { print $1 }')"
	(cd "$SRCDIR" && tar cvf - . 2> $DESTDIR/backups/daily.1/tvf) | reblock -e "$blocks" $[128*1024] 300 | gzip > daily.1/archive
else
	(cd "$SRCDIR" && tar cvzf - .) > daily.1/archive 2> daily.1/tvf 
fi

if [ "$mode" = normal ]
then
	if [ "$day_of_week" = Sun ]
	then
		rm -rf weekly.2
		mv weekly.1 weekly.2
		mkdir weekly.1
		cp daily.1/* weekly.1/.
	fi

	if [ "$day_of_month" = 01 ]
	then
		rm -rf monthly.2
		mv monthly.1 monthly.2
		mkdir monthly.1
		cp daily.1/* monthly.1/.
	fi
fi

# this isn't really needed...  In fact, it's pretty much a NOOP, unless there's an old-style automounter involved or something
#cd "$SRCDIR"