#!/bin/bash

#################### Config #####################

# The OpenMRS runtime properties file
OPENMRS_PROP_FILE="/usr/share/tomcat6/.OpenMRS/openmrs-runtime.properties"

# Destination directory for backups
BACKUP_DEST_DIR="/home/emr-admin/openmrs_backups"

# Destination filename forcompressed dump file names
BACKUP_DEST_FILE="openmrs-db-`date '+%Y-%m-%d'`.gz"

# Number of days to keep dumps before deletion (0 = never delete)
DUMP_KEEP_DAYS=100

# Logging tag
LOGGING_TAG="OPENMRS-BACKUP"

#################### Functions #####################

# Fail function to record error in syslog
fail() {
	logger -t $LOGGING_TAG -p local0.crit $1
	exit
}

#################### Main #####################

# Check runtime properties file exists
if ! [ -e "$OPENMRS_PROP_FILE" ]; then
	fail "Specified OpenMRS runtime properties file does not exist"
fi

# Read properties from properties file
dbuser=`sed '/^\#/d' "$OPENMRS_PROP_FILE" | grep 'connection.username' | tail -n 1 | cut -d "=" -f2-`
dbpass=`sed '/^\#/d' "$OPENMRS_PROP_FILE" | grep 'connection.password' | tail -n 1 | cut -d "=" -f2-`
dburl=`sed '/^\#/d' "$OPENMRS_PROP_FILE" | grep 'connection.url' | tail -n 1 | cut -d "=" -f2-`

# Check properties could be read
if [ -z $dbuser ] || [ -z $dbpass ] || [ -z $dburl ]; then
	fail "Unable to read OpenMRS runtime properties"
fi

# Extract database name from connection URL
if [[ $dburl =~ /([a-zA-Z0-9_\-]+)\? ]]; then
        dbname=${BASH_REMATCH[1]}
else
        dbname="openmrs"
fi

# Check destination directory exists and is writable
if ! [ -d "$BACKUP_DEST_DIR" ] || ! [ -w "$BACKUP_DEST_DIR" ]; then
	fail "Backup destination directory does not exist or is not writable"
fi

dumpfile="$BACKUP_DEST_DIR/$BACKUP_DEST_FILE"

# Delete dump file if it already exists
if [ -e $dumpfile ]; then
	rm $dumpfile
fi

# Dump OpenMRS database and gzip result
mysqldump -u$dbuser -p$dbpass $dbname | gzip -c > $dumpfile

# Check dump was successful and new dump file exists
if [ ${PIPESTATUS[0]} -eq 0 ] && [ -e $dumpfile ]; then
	logger -t $LOGGING_TAG -p local0.info "Database dump successful"
else
	fail "Unable to dump database (name=$dbname, user=$dbuser)"
fi

# Optionally delete older dumps
if [ $DUMP_KEEP_DAYS -ne 0 ]; then
	find "$BACKUP_DEST_DIR" -name "*.gz" -type f -mtime +${DUMP_KEEP_DAYS} -delete
fi
