#!/bin/sh

PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH

# rsync-wrapper shell script.  Copyright 2002-2008, Mike Bombich
# This script is executed when the root user from a remote machine
# successfully authenticates with a public key.  The privileges
# of that user on this server are limited to the functionality of this script.
# This wrapper will verify that the client is sending an rsync command.
# If it is, then the original, unaltered command is run, if not, 
# an error is returned.
##
##
#
# NOTE: If the path on the remote host (e.g. the machine you're rsyncing to 
# that will be running this script) contains spaces, this script will break rsync
#
##

log="/Library/Logs/rsync.log"
allowDelete=true

if [ "${SSH_ORIGINAL_COMMAND:=UNSET}" == "UNSET" ]; then
        echo "root login is not permitted to this machine via public key authentication."
        exit 127
fi

declare -a command
command=($SSH_ORIGINAL_COMMAND)

# Make sure the original command is rsync
if [ "${command[0]}" == "/usr/local/bin/rsync" ]; then
	# Ensure that --server is on the command line, to enforce running
	# rsync in server mode.

	server=false
	for arg in "${command[@]}"; do
		if [ "$arg" == "--delete" -a "$allowDelete" == "false" ]; then
			echo "You may not use rsync with the delete flag on this server!" >> $log
			exit 127
		fi
		if [ "$arg" == "--server" ]; then
			server=true
		fi
	done

	# If the command is an rsync server, execute the original command
	if [ "$server" == "true" ]; then
		$SSH_ORIGINAL_COMMAND
	else
		echo "This does not appear to be a valid rsync request" >> $log
		exit 127
	fi

else
	echo "Command rejected by rsync_wrapper: `date`: ${command[@]}" >> $log
	echo "That command is not allowed with the root account via public key authentication."
	exit 127
fi
