#!/bin/zsh
exec 1>&2
env | grep RSYNC

set -x

[[ $RSYNC_MODULE_NAME != 'snaprep_new' ]] && exit 0

f=( $RSYNC_MODULE_PATH/.snapshot.[0-9]*(N) )
if (($#f == 0)); then
	exit 0
elif (($#f > 1)); then
	rm -rf $f || exit $?
else
	ts=${f##*.}
	d=$RSYNC_MODULE_PATH:h
	if [[ -a $d/.snapshot.$ts ]]; then
		rm -rf $f || exit $?
	else
		rsync -aA --exclude=/.snapshot.\* --link-dest=$RSYNC_MODULE_PATH/ $RSYNC_MODULE_PATH/ $d/$ts/ || exit $?
		mv $f $d/ || exit $?
	fi
fi