#!/bin/bash

# This script is designed to grab a nightly snapshot of Zimbra so that in the case of
# a server failure we can recover to the previous day's data.

# This script performs three rsyncs between our production and backup mail servers.
# The first rsync is performed while Zimbra is live.  The second rsync is performed
# after Zimbra is stopped.  The third rsync is simply to catch any potential file
# changes since the second sync.

# In order to be able to start and stop Zimbra via this script, SSH keys were
# generated under the root user on this server.  The root's public SSH key was added
# to the Zimbra user on the production server's "~/.ssh/authorized_keys" file.

# Written by Anthony Hoppe.  ahoppe@mpcsd.org

log="/var/log/zmrsync2.log"

# 1. Sync while Zimbra is live.

	time=$(date +"%r")
	date=$(date +"%m-%d-%Y")

		echo "First rsync process initiated at" $time "on" $date"." > $log

		rsync -zaHv --rsh=/usr/bin/ssh --stats --delete root@10.1.1.37:/opt/zimbra /opt/ >> $log

	time=$(date +"%r")
	date=$(date +"%m-%d-%Y")

		echo "First rsync process completed at" $time "on" $date"." >> $log

# 2. Stop Zimbra.

	time=$(date +"%r")
	date=$(date +"%m-%d-%Y")

		echo "Zimbra shutdown initiated at" $time "on" $date"." >> $log

		ssh zimbra@10.1.1.37 'date +"%r"; zmcontrol stop; date +"%r"' >> $log

	time=$(date +"%r")
	date=$(date +"%m-%d-%Y")

		echo "Zimbra shutdown complete at" $time "on" $date"." >> $log

# 3. Sync Zimbra while it's down (this is so no file changes take place). 

	time=$(date +"%r")
	date=$(date +"%m-%d-%Y")

		echo "Second rsync process initiated at" $time "on" $date"." >> $log

		rsync -zaHv --rsh=/usr/bin/ssh --stats --delete root@10.1.1.37:/opt/zimbra /opt/ >> $log
	
	time=$(date +"%r")
	date=$(date +"%m-%d-%Y")

		echo "Second rsync process completed at" $time "on" $date"." >> $log

# 4. Sync one last time, just in case.  This should be very quick.

	time=$(date +"%r")
	date=$(date +"%m-%d-%Y")

        	echo "Third rsync process initiated at" $time "on" $date"." >> $log

		rsync -zaHv --rsh=/usr/bin/ssh --stats --delete root@10.1.1.37:/opt/zimbra /opt/ >> $log

	time=$(date +"%r")
	date=$(date +"%m-%d-%Y")

		echo "Third rsync process completed at" $time "on" $date"." >> $log

# 5. Lastly, bring Zimbra back up.

	time=$(date +"%r")
	date=$(date +"%m-%d-%Y")

		echo "Zimbra startup initiated at" $time "on" $date"." >> $log

		ssh zimbra@10.1.1.37 'date +"%r"; zmcontrol start; date +"%r"' >> $log

	time=$(date +"%r")
	date=$(date +"%m-%d-%Y")

		echo "Zimbra startup completed at" $time "on" $date"." >> $log

