#!/bin/sh
#
# File: mmDeltaBackup.sh
# Desc: This script will do a backup of all the vital config on the appliance
# There are two types of backup that the script can do:
# "full" - A .tgz of all the files included in the backup
# "delta" - A rsync delta of all the files included in the backup what was last backed up 
# either (full or delta)
#

if [ $# -lt 2 ]
then
	echo "error: missing arguments."
	echo "Usage: mmDeltaBackup.sh <type> <backup-folder>"
	exit 1
fi

CURR_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"

TYPE=$1
DESTINATION=$2
FILE_FROM=$CURR_DIR/mmDeltaBackup.files.conf

FULL_BACKUP_NAME=full.tgz
FULL_BACKUP_PATH=$DESTINATION/$FULL_BACKUP_NAME

REF_NAME=ref
REF_PATH=$DESTINATION/$REF_NAME
[ -d "$REF_PATH" ] || mkdir -p "$REF_PATH"

# Make sure that backup can only be read by us.
chmod 700 $DESTINATION

if [ $TYPE == "delta" ] && [ ! -f "$FULL_BACKUP_PATH" ]
then
	# We are doing delta and full backup doesn't exist we need full.
	TYPE=full
fi


if [ $TYPE == "full" ]
then
	# remove older files
	rm -rf $REF_PATH/*
	rm -f $FULL_BACKUP_PATH
	# removing rsync.log so it will not grow indefinitily
	rm -f /var/log/rsync.log

	# rsync files to <REF>
	rsync -ra --log-file=/var/log/rsync.log --files-from=$FILE_FROM / $REF_PATH

	# create backup
	(cd $DESTINATION && tar -czf $FULL_BACKUP_NAME $REF_NAME)

	echo $FULL_BACKUP_NAME

elif [ $TYPE == "delta" ]
then

	DELTA_BACKUP_NAME=delta
	DELTA_BACKUP_PATH=$DESTINATION/$DELTA_BACKUP_NAME
	rm -f $DELTA_BACKUP_PATH

	# rsync files creating a batch
	rsync -ra --log-file=/var/log/rsync.log --write-batch $DELTA_BACKUP_PATH --files-from=$FILE_FROM / $REF_PATH

	# remove delta file shell script
	rm -f $DELTA_BACKUP_PATH.sh

	echo $DELTA_BACKUP_NAME
else
	echo "Incorrect backup type"
	exit 2
fi

