#!/bin/bash
# set -x
# Back up all the important stuff from feynman
# This doesn't check if the data has gotten bigger than the data store will
# hold.

function checkRC
{
    rc=$1
    name=$2

    if [ $rc != 0 ]
    then
        echo "===== $name failed with rsync rc=$rc ====="
    fi
}
function dumpDB
{
	DB=$1
	mysqldump -u root -B $DB -r $DBDIR/$DB/`date +%u`-$DB.`date +%a`
	echo "Backed up $DB"
}


# Where do the backups go?
LOGIN=user@remoteHost
DRIVE=/media/usbDrive
BRAHE=$LOGIN:$DRIVE
if [ "$1" != "" ]
then
    BRAHE=$1
fi

# Command to verify the remote server is ready.
VERIFYCMD="grep $DRIVE /etc/mtab"

# Where to save MySQL dumps
DBDIR="/home/httpd/db"
DATE=`date`

# Backup the following directories
DIR1="/home/user"
EXCL1=--exclude-from=/home/user/.rsync/local
DIR2="/home/httpd"

# =============================================================================
# Check to make sure the backup server has the external drive mounted.
ssh $LOGIN $VERIFYCMD 2>&1 > /dev/null
if [ $? = 1 ]
then
    echo "== Backup of `uname -n` failed: remote server not ready"
    echo "== Command failed on remote server: $VERIFYCMD"
    exit 1
fi


# =============================================================================

echo ""
echo ""
echo "== Backing up `uname -n` to $BRAHE."
echo "== Started @ $DATE "

# Keep a weeks worth of backups.
echo "== MySQL Backups: "
dumpDB mysql
dumpDB amarok

echo "== Directory: $DIR1"
rsync -axq --safe-links $EXCL1 $DIR1 $BRAHE
checkRC $? "$DIR1"

echo "== Directory: $DIR2"
rsync -axq --safe-links $DIR2 $BRAHE
checkRC $? "$DIR2"

DATE=`date`
echo "Backups complete @ $DATE"


