#!/bin/bash
################################################################################
# Configuration
################################################################################
## Directory to backup
SOURCE_DIRECTORY=""
## The directory to build the backup file in (best left to /tmp/
BUILD_DIRECTORY=""
## The email address to mail about errors.
EMAIL=""
## The email address to encrypt the backup to (Recipient to GNUPG).
ENCRYPT_TO=""
## A file containing the list of directories to exclude from the daily backup.
DAILY_EXCLUDE=""
## A file containing the list of directories to exclude from the weekly backup.
WEEKLY_EXCLUDE=""
## The remote host to send the backup to.
DESTINATION_HOST=""
## The directory on the remote host to send the backup to.
DESTINATION_DIR=""
## Options passed to SCP. Useful to specify a unpassword key for automatic updates.
# SSH_OPTIONS="-i KEY"

################################################################################
################################################################################
# No need to touch anything below here.
################################################################################
################################################################################
if [ $# != 1 ]; then
	echo "Usage: backup.sh [daily|weekly]"
	exit
fi

if [ $1 = "daily" ]; then
	EXCLUDE_FILE=$DAILY_EXCLUDE
elif [ $1 = "weekly" ]; then
	EXCLUDE_FILE=$WEEKLY_EXCLUDE
else
	echo "Usage: backup.sh [daily|weekly]"
	exit
fi

DATE="`date +%Y%b%d_%H%M`"
FILENAME="ganymede_${1}_${DATE}.tar.bz2.gpg"
DIRECTORYFILE="${BUILD_DIRECTORY}${FILENAME}"
DEST="${DESTINATION_HOST}:${DESTINATION_DIR}"

tar cvp --sparse ${SOURCE_DIRECTORY} \
--exclude-from ${EXCLUDE_FILE} \
| bzip2 \
| gpg -e -r ${ENCRYPT_TO} \
> $DIRECTORYFILE

scp $SSH_OPTIONS $DIRECTORYFILE $DEST
if [ $? != 0 ]; then
	echo "Backup FAILED. Transfer of backup file failed."
	echo "Backup FAILED. Transfer of backup failed." | mail -s "Daily backup failed" \
	${EMAIL}
	exit
fi

# Get some MD5s.
sourceMD5=`md5sum ${DIRECTORYFILE}`
if [ $? != 0 ]; then
	echo "Backup FAILED. Could not get local MD5 sum."
	echo "Backup FAILED. Could not get local MD5 sum." | mail -s "Backup failed" ${EMAIL}
	exit
fi
sourceMD5=`echo ${sourceMD5} | awk '{print $1}'`

destMD5=`ssh $SSH_OPTIONS $DESTINATION_HOST md5sum ${DESTINATION_DIR}${FILENAME}`
if [ $? != 0 ]; then
	echo "Backup FAILED. Could not get remote MD5 sum."
	echo "Backup FAILED. Could not get remote MD5 sum." | mail -s "Backup failed" ${EMAIL}
	exit
fi
destMD5=`echo ${destMD5} | awk '{print $1}'`

# Check if the MD5 sums match
if [ ${sourceMD5} != ${destMD5} ]; then
    echo "Backup FAILED. MD5 check did not pass."
    echo "Backup FAILED. MD5 check did not pass." | mail -s "Backup failed" ${EMAIL}
else
    echo "Backup successful."
fi

## Remove the local copy.
rm $DIRECTORYFILE

