#!/bin/bash

# fcnsbackup
#
# $Id: fcnsbackup 1756 2013-03-15 17:41:10Z jhealy $
#
#
#
# THIS SCRIPT IS NO LONGER MAINTAINED.  IT IS KEPT FOR HISTORICAL
# PURPOSES ONLY.  SEE THE rsync_snapshot_fcns SCRIPT FOR THE CURRENT
# BACKUP METHOD.
#
#
#
# This script pauses mirroring on the FirstClass core server, performs
# a backup of the mirrored directories, and then resumes mirroring.
#
# Backups are performed using rsync, so incremental backups should
# complete relatively quickly.
#
# SSH is used for the transport, with a paswordless SSH key used to
# authenticate the user to the backup server.  The server must have
# the remote account set up correctly, and must have the SSH key
# installed for that user.
#

# Program to use to control the FC core server
FCSCTL="/usr/sbin/fcsctl"


####
#### Don't edit below this mark unless you know what you're doing
####


# Location of lockfile to ensure that two backups don't run simultaneously
LOCKFILE="/tmp/lock.fcnsbackup"

# By default, we do not have the lock
LOCK=0

# By default, the mirror is not paused
MIRRORPAUSED=0

# This function is called when the script is interrupted
# It prints a warning to the user
function die() {
    echo "fcnsbackup: die: ${1}" 1>&2
    exit 1;
}

# This function is called when the script exits (even if interrupted)
# It cleans up any temporary files and restarts mirroring on the server
function cleanup() {
    echo "fcnsbackup: cleaning up..."

    if [ ${LOCK} -eq 1 ]; then

	if [ ${MIRRORPAUSED} -eq 1 ]; then
	    echo "fcnsbackup: resuming mirroring on FirstClass server"
	    ${FCSCTL} continue
	fi

	echo "fcnsbackup: removing lockfile"
        rm -f $LOCKFILE
    fi
}


# Trap for interrupt signals, so we can shut down cleanly
trap 'die "script was interrupted at `date`"' SIGHUP SIGINT SIGQUIT SIGTERM

# Universal trap for any exit (clean or interrupted)
trap 'cleanup' 0


###
### Main script
###

# make sure we're not running as root
USERID=$(id -u)

if [ $USERID -eq 0 ]; then
    die "script cannot execute as UID 0 (root)"
fi

# Credit to O'Reilly's "Unix Power Tools" for this lock script
if (umask 222; echo $$ >$LOCKFILE) 2>/dev/null; then

    # we got the lock
    LOCK=1

    # Pause mirroring
    echo -n "fcnsbackup: pausing mirroring on FirstClass server: "
    MIRRORMESG=$(${FCSCTL} pause)
    MIRRORSTAT=$?

    if [ ${MIRRORSTAT} -eq 0 ]; then
	MIRRORPAUSED=1
	echo "paused"
	# give the server a few seconds to suspend the mirror
	sleep 5
    else
	echo ""
	die "mirroring could not be paused; FC said ${MIRRORMESG}"
    fi

    /Users/fcadmin/rsync_snapshot_sender /Users/fcadmin/newman.conf

    RSYNC_STATUS=$?

    if [ ${RSYNC_STATUS} -ne 0 ]; then
	die "rsync exited with status ${RSYNC_STATUS}"
    fi

else
   set x `ls -l $LOCKFILE`
   die "unable to get lock file from user $4 (working since $8 $7 $9)"
fi

exit 0
