#!/bin/sh
progname=${0##*/}
toppid=$$

# What protocol we are using, the utility name and flags
PROTO=ssh
RSYNC=rsync
RSYNC_FLAGS="-az --delete -e "
LOGCMD=logger
LOGID=rsyncondemand # The name of our /var/log/messages entries
LOG_FLAGS="-t $LOGID" # Flags for the logger interface

# Generic bomb routine in case things go south
bomb()
{
	cat >&2 <<ERRORMESSAGE

ERROR: $@
*** ${progname} aborted ***
ERRORMESSAGE
	kill ${toppid}
	exit 1
}

usage()
{
	cat <<_usage_
Usage: ${progname} help
Usage: ${progname} [options arguments...]
Usage: ${progname} [-s [srchost:]/dir] [-d [dsthost:]/dir] [-f "rsync flags"]
Options:
    -s SRC	 Synchronize from source host:/directory or just directory
	-d DST	 Synchronize to host:/directory or just directory
	-f flags Override the default rsync flags with custom flags. Must be
             enclosed in double quotes.
Examples:
 Sync from local directory /usr/local/mudserver to arachnos:/netbackups
     ${progname} -s /usr/local/mudserver -d arachnos:/netbackups
 Sync midge:/home to /u00/midge not using compression and remote shell
     ${progname} -s midge:/home -d /u00/midge -f "-a --delete -e rsh"
_usage_
}

# Verify that we actually have proto, rsync, and log util installed
for i in $PROTO $RSYNC $LOGCMD
do
	if ! type ${i} >/dev/null; then
		$LOGCMD $LOGID "${i} not found"
		bomb "${i} not found"
	fi
done

# Parse the input, we need a src and destination
if ! type getopts >/dev/null 2>&1; then
	bomb "/bin/sh shell is too old; try ksh or bash"
fi

while getopts s:d: ch; do
	case ${ch} in
		s)
			SRC=${OPTARG}
			;;
		d)
			DST=${OPTARG}
			;;
		f)
			$RSYNC_FLAGS=${OPTARG}
			;;
		p)
			$PROTO=${OPTARG}
			;;
		*)
			usage
			;;
	esac
done
shift $((${OPTIND} - 1))

$LOGCMD $LOGID "Starting $RSYNC operation from $SRC to $DST"
$RSYNC $RSYNC_FLAGS $PROTO $SRC $DST
$LOGCMD $LOGID "Finished $RSYNC operation from $SRC to $DST"

exit 0

