#!/bin/bash
#===============================================================================
#
#          FILE:  ocbackup.sh 
# 
#         USAGE:  ./ocbackup.sh 
# 
#   DESCRIPTION:  Creates a backup of OpenClinica
# 
#       OPTIONS:  ---
#   REQUIRMENTS:  ---
#          BUGS:  ---
#         NOTES:  ---
#        AUTHOR:  Shaun Martin (Systems Administrator), smartin@akazaresearch.com
#       COMPANY:  Akaza Research LLC
#       VERSION:  1.0
#       CREATED:  02/12/2009 17:15:49 EST
#      REVISION:  ---
#===============================================================================
# Copyright 2009 Akaza Research LLC

# Set Environment variables to your system.

scriptdir=/usr/local/oc/backup
backupdir=$scriptdir/backup
logdir=$scriptdir/logs

#Set tomcatroot to your TOMCAT_HOME, no need to change the others unless you are not using a standard structure.
tomcatroot=/usr/local/tomcat
webapps=$tomcatroot/webapps

#When this dow is seen on the zips it starts the weekly zip process.
dowls=Mon

#Set User and Password for user you want to do the backup. Set the host and location of pg_dump
export PGUSER=clinica
export PGPASSWORD=clinica
pghost=localhost
pgbin=/opt/PostgreSQL/8.4/bin

#List your database names
databases=( openclinica openclinica_test )

#List your properties directories (JUST REPLACE OpenClinicaXXX WITH YOUR WEBAPP NAMES)
propdir=( OpenClinica OpenClinica_test )

#List your openclinica.data directories (IF NAMED THE SAME AS DATABASE.data LEAVE ALONE)
#ocdatadir=( ${databases[0]}.data ${databases[1]}.data ${databases[2]}.data ) 

#Below are the programs and options we will use for zipping and copying
zip=tar
zipopts=-cvf
copy=cp
copyopts=-rfv

# DO NOT EDIT BELOW THIS LINE

# Set Date
day=`date +%d`
yyyy=`date +%Y`
mm=`date +%m`
filedate=$mm-$day-$yyyy
# Set Time
hour=`date +%H`
min=`date +%M`
filetime=$hour-$min
# Set Time Stamps
timestamp=$filedate--$filetime
pgfile=$timestamp.db
day2=`date +%a`
numdatabases=${#databases[*]}
numpropdir=${#propdir[*]}

twoweek=yes
year=no

#Function

# Backup
function backup ()
{

#VACUUM DB
$pgbin/vacuumdb -a -f -z

# Postgres Backup
for (( i=0;i<$numdatabases;i++)); do
    $pgbin/pg_dump --format=c -h $pghost -o ${databases[${i}]} > $backupdir/postgres/${databases[${i}]}-$pgfile
done

#Copy datainfo.properties
for (( i=0;i<$numpropdir;i++)); do
	backupdirname=${propdir[${i}]}
	propdirs="$webapps/$backupdirname/WEB-INF/classes"
	$copy $copyopts $propdirs/datainfo.properties $backupdir/openclinica.data/$backupdirname-datainfo-$timestamp >> $logdir/copy.log 


	#  $copy $copyopts ${propdir[${i}]}/datainfo.properties $backupdir/openclinica.data/datainfo-oc1-$timestamp >> $logdir/copy.log
done

#Copy OC Data Directories
for (( i=0;i<$numdatabases;i++)); do
	ocdatadir=${databases[${i}]}.data
	$copy $copyopts $tomcatroot/$ocdatadir $backupdir/openclinica.data/$ocdatadir-$timestamp >> $logdir/copy.log

	#For Individual non standard locations (WHEN DATA DIRECTORY IS NOT NAMED THE SAME AS THE DATABASE)
	#   $copy $copyopts $tomcatroot/${ocdatadir[${1}]} $backupdir/openclinica.data/${ocdatadir[${1}]}-$timestamp >> $logdir/copy.log
done

# Zipping Postgres and OC Data files 
cd $backupdir; $zip $zipopts $scriptdir/zips/$day2-$timestamp.tar . >> $logdir/zip.log
zip
}

function zip ()
{
if [ -r $scriptdir/zips/$dowls* ]; then
	dow=`ls $scriptdir/zips/$dowls*`
else
	dow=$dowls
fi
# Sets the rotation day for weekly rotations by the DOW environment variable above.
if [ -r $dow ]; then
	if [ $twoweek = yes ]; then
	2weekzipvar
	else
	weekzipvar
	fi
else
cleanup
fi
}

function weekzipvar ()
{
if [ -r $scriptdir/zips/week1* ]; then

	if [ -r $scriptdir/zips/week2* ]; then

		if [ -r $scriptdir/zips/week3* ]; then

			if [ -r $scriptdir/zips/week4* ]; then
				if [ $year = yes ]; then
				month		
				else
				week=week5
				weekzip
				fi
			else
			week=week4
			weekzip
			fi
		else
		week=week3
		weekzip
		fi
	else
	week=week2
	weekzip
	fi
else
week=week1
weekzip
fi
}

function month ()
{
	if [ $year = yes ]; then
		if [ -r $scriptdir/zips/month-$mm-$yyyy.zip ]; then
		month=month-$mm-$yyyy-2
		monthzip
		else
		month=month-$mm-$yyyy
		monthzip
		fi
	else
	#Week2 becomes Week1
	week1sedcp=`ls $scriptdir/zips/week2*`
	week1rename=`echo $week1sedcp | sed -e "s/week2/week1/"`
	rm $scriptdir/zips/week1* >> $logdir/del.log
	mv $week1sedcp $week1rename >> $logdir/copy.log

	#Week3 becomes Week2
	week2sedcp=`ls $scriptdir/zips/week3*`
	week2rename=`echo $week2sedcp | sed -e "s/week3/week2/"`
	mv $week2sedcp $week2rename >> $logdir/copy.log

	#Week4 becomes Week3
	week3sedcp=`ls $scriptdir/zips/week4*`
	week3rename=`echo $week3sedcp | sed -e "s/week4/week3/"`
	mv $week3sedcp $week3rename >> $logdir/copy.log

	#Week5 becomes Week4
	week4sedcp=`ls $scriptdir/zips/week5*`
	week4rename=`echo $week4sedcp | sed -e "s/week5/week4/"`
	mv $week4sedcp $week4rename >> $logdir/copy.log
	fi
}

function 2weekzipvar ()
{
if [ -r $scriptdir/zips/week1* ]; then

	if [ -r $scriptdir/zips/week2* ]; then
	2week
	else
	week=week2
	weekzip
	fi
else
week=week1
weekzip
fi
}


#function weekzipvar ()
#{
#week2
#else
#week=week1
#weekzip
#fi

function 2week ()
{
echo Weekly ZIP >> $logdir/copy.log
twoweeksedcp=`ls $scriptdir/zips/week2*`
twoweekrename=`echo $twoweeksedcp | sed -e "s/week2/week1/"`
rm $scriptdir/zips/week1* >> $logdir/del.log
mv $twoweeksedcp $twoweekrename >> $logdir/copy.log
week=week2
cd $scriptdir/zips/; $zip --exclude=week* --exclude=month* $zipopts $week-$timestamp.tar . >> $logdir/zip.log
rm -v $scriptdir/zips/Mon* >> $logdir/del.log
rm -v $scriptdir/zips/Tue* >> $logdir/del.log
rm -v $scriptdir/zips/Wed* >> $logdir/del.log
rm -v $scriptdir/zips/Thu* >> $logdir/del.log
rm -v $scriptdir/zips/Fri* >> $logdir/del.log
rm -v $scriptdir/zips/Sat* >> $logdir/del.log
rm -v $scriptdir/zips/Sun* >> $logdir/del.log
cleanup
}

function weekzip ()
{
# Zips the the daily zip files into a weekly zip file and deletes daily zips.
echo Weekly ZIP >> $logdir/copy.log
cd $scriptdir/zips/; $zip --exclude=week* --exclude=month* $zipopts $week-$timestamp.tar . >> $logdir/zip.log
rm -v $scriptdir/zips/Mon* >> $logdir/del.log
rm -v $scriptdir/zips/Tue* >> $logdir/del.log
rm -v $scriptdir/zips/Wed* >> $logdir/del.log
rm -v $scriptdir/zips/Thu* >> $logdir/del.log
rm -v $scriptdir/zips/Fri* >> $logdir/del.log
rm -v $scriptdir/zips/Sat* >> $logdir/del.log
rm -v $scriptdir/zips/Sun* >> $logdir/del.log

if [ $year = yes ]; then
	if [ -r $scriptdir/zips/week4* ]; then
	month
	cleanup
	else
	week=week4
	cleanup
	fi
else
	if [ -r $scriptdir/zips/week5* ]; then
	month
	cleanup
	else
	cleanup
	fi
fi
}

function monthzip ()
{
# Zips the weekly files into a monthly file and deletes Weekly zips.
echo Monthly ZIP >> $logdir/copy.log
cd $scriptdir/zips/; $zip --exclude=month*  $zipopts $scriptdir/zips/$month.tar . >> $logdir/zip.log
rm -v $scriptdir/zips/week* >> $logdir/del.log
cleanup
}

function cleanup ()
{
# Remove Backup Directory and TimeStamp the Log Files
rm -rvf $scriptdir/backup >> $logdir/del.log
echo Backup End -- `date` >> $logdir/zip.log
echo Backup End -- `date` >> $logdir/copy.log
echo Backup End -- `date` >> $logdir/del.log
}


# Begin of actual backup duties.

#Creates Directory structure and timestamps logs
if [ -d $scriptdir/logs ] ;then
echo Backup Start -- `date` >> $logdir/zip.log
echo Backup Start -- `date` >> $logdir/copy.log
echo Backup Start -- `date` >> $logdir/del.log
else
mkdir -p $scriptdir/logs
mkdir -p $scriptdir/zips
echo Backup Start -- `date` >> $logdir/zip.log
echo Backup Start -- `date` >> $logdir/copy.log
echo Backup Start -- `date` >> $logdir/del.log
fi

#Creates backupdir and executes the backup
if [ -d $backupdir ] ;then
backup
else
mkdir -p $backupdir/postgres
mkdir -p $backupdir/openclinica.data
backup
fi
