#!/bin/bash 
#
# Backup script for both Mysql and Silvertripe
#

#
# This script is designed to backup a single Silverstripe Installation along with its MySQL db.
# The script currently has very little in the way of smarts, and is really only built for a unix environment.
# 
# Usage:  The script is very straight forward.  You need to make sure that the following variables are set for
# YOUR specific environment
#
#	BACKUPDIR - The location that you wish to store the backups
#	SSPATH - The path to your silverstripe installation. eg /var/www/silverstripe
#	SSDB - The name of the silverstripe database								
#	SSDBUSER - The name of the user that is able to access the silverstripe database
#	SSDBPASS - The password of the user that is able to access the silverstripe database
#	SSDBSERVER - The host on which the silverstripe database is hosted.
#
# You may want to change the SSTEMPROOT, but thats up to you.
#
# Finally, make sure that the user you are executing the script as is able to write the backup file to the backup dir.


#Copyright (c) 2009, SilverStripe Australia PTY LTD - www.silverstripe.com.au
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#    * Neither the name of SilverStripe nor the names of its contributors may be used to endorse or promote products derived from this software
#      without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
#LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
#GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
#STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
#OF SUCH DAMAGE.
#

PROGNAME=$(basename $0)							# Provide a backlink to the script name for later use

PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"	# Define the PATH.


DATE=`date +%Y-%m-%d_%Hh%Mm`						# Datestamp e.g 2002-09-21
DOW=`date +%A`								# Day of the week e.g. Monday
DNOW=`date +%u`								# Day number of the week 1 to 7 where 1 represents Monday
DOM=`date +%d`								# Date of the Month e.g. 27
M=`date +%B`								# Month e.g January
W=`date +%V`
UNIXDATE=`date +%s`

BACKUPDIR="/var/backup"							# Backup direcory location

SSPATH="/var/www/silverstripe"						# Silverstripe path

SSDB="silverstripe"							# Silverstripe connection details
SSDBUSER="silverstripe"
SSDBPASS="password"
SSDBSERVER="localhost"

OPT=""									# Specific MySQL options if you wish to pass them


SSTEMPROOT="/var/tmp"							# Define the temp path for the backups
SSTEMPMASK="${SSDB}_${UNIXDATE}"
SSTEMP=$SSTEMPROOT/$SSTEMPMASK

function clean_up {							# Provide a cleanup routine, to be extended later
	rm -rf $1 
}


function error() {							# Provide a method to capture errors and report them in a somewhat useful manner
  local PARENT_LINENO="$1"
  local MESSAGE="$2"
  local CODE="${3:-1}"
  if [[ -n "$MESSAGE" ]] ; then
    echo "Error on or near line ${PARENT_LINENO}: ${MESSAGE}; exiting with status ${CODE}"
    else
    echo "Error on or near line ${PARENT_LINENO}; exiting with status ${CODE}"
  fi
  exit "${CODE}"
}

trap "error ${LINENO}" ERR

trap clean_up SIGHUP SIGINT SIGTERM


if [ ! -e ${BACKUPDIR} ] 						# Create the backup location if it does not exist. 
	then
	mkdir -p ${BACKUPDIR} 
fi

mkdir -p ${SSTEMP}							# Create the temp location for the backup process.

if [ $? -eq 1 ]								# Make sure that the temp path creates.
then
error "Cannot create Temp directory - Aborting" 
fi


## 
# DATABASE DUMP FUNCTION
#
# 
#
dbdump () {
	mysqldump --user=${SSDBUSER} --password="${SSDBPASS}" --host=${SSDBSERVER} ${OPT} $1 > ${SSTEMP}/$2
	if [ ! ${?} -eq 0 ]
		then
		error "Mysql dump failed" 
	else
	cp ${SSTEMP}/$2 ${SSPATH}
fi
}

## 
# Silverstripe dump function
#
#

ssdump () {
	tar -C ${SSPATH} -zcf $1 ${SSPATH} 
	if [ $? -eq 1 ]
		then
		error "Silverstripe backup process failed." 
fi
}

##
# Execute the backup
#
#

echo "Running the Mysqldump"
dbdump ${SSDB} ${SSDB}_${DATE}.sql

if [ $? -eq 0 ]
	then
	echo "Mysqldump for database ${SSDB} successful"
fi

echo "running the backup now..."
ssdump ${BACKUPDIR}/${SSDB}_${DATE}.tar.gz

if [ $? -eq 0 ]
	then
	echo "Silverstripe backup successful"
fi

# Clean up the temp data on a successful exit

clean_up ${SSTEMP}
clean_up ${SSPATH}/${SSDB}_${DATE}.sql 



