#!/usr/local/bin/bash
# Herakles backup-script using rsync over ssh
# website: http://www.adslweb.net/tools/herakles
#
# License: GPLv2
#
## Definitions
#

# SRC_LIST
# Location of the file with directories who
# must be transfered.
SRC_LIST="/usr/local/backup/herakles/backup_list"

# DST_HOST
# FQDN or IP of the host where it has to be
# transfered
DST_HOST="tank.adslweb.net"

# DST_USERNAME
# Username on the backup-server
DST_USERNAME="backup"

# DST_PATH
# Destination path on the backup-server
DST_PATH="/usr/data/backup/snapshots"

# LOG_FILE
LOG_FILE="/var/log/herakles"

# RSYNC
# Location of the rsync tool
RSYNC="/usr/local/bin/rsync"

# RSYNC_OPTIONS
RSYNC_OPTIONS="--delete -az --exclude=log/"

# SSH
# Location of the SSH tool
SSH="/usr/bin/ssh"

# LOCKFILE
LOCKFILE="/var/run/herakles.pid"

##### END OF DEFINITIONS
###################################################

# Herakles version:
VERSION="0.0.2"  

if [ -f $LOCKFILE ]
then
	echo "[ERROR] Script is still running"
        echo "or $LOCKFILE is still there!"
        echo "" 
        echo "Check if pid `cat $LOCKFILE` still exists"
        logger "[HERAKLES] Could not start there is a lock on pid `cat $LOCKFILE`"
        exit 1
else
	echo $$ > $LOCKFILE
        logger "[HERAKLES] Starting update using pid `cat $LOCKFILE`"
fi 

DATESTART=`date`

exec 1> $LOG_FILE
exec 2>&1

####
# Building on the remote system the directory structures
echo -n "Building Directory structures "
for source_list in `cat $SRC_LIST`;
do
	BACKUP_PATH=$DST_PATH$source_list
        $SSH $DST_USERNAME@$DST_HOST mkdir -p $BACKUP_PATH
                
done
echo " [ DONE ] "

# Starting with rsync
echo "Synchronising the data"
for source_list in `cat $SRC_LIST`;
do
	BACKUP_PATH=$DST_PATH$source_list
	echo -n " - $source_list " 
	$RSYNC $RSYNC_OPTIONS -e $SSH $source_list/ $DST_USERNAME@$DST_HOST:$BACKUP_PATH
	echo " [ DONE ] "
done 
echo "================================================"
echo $DATESTART
date
echo "================================================"
logger "[HERAKLES] Stopping update using pid `cat $LOCKFILE`"
rm $LOCKFILE

2>&-
1>&-

