#!/bin/sh

set -u

BASE="$(dirname "$0")"

# RSYNC_OPENSDE_LOCATION
# RSYNC

# options
RSYNCOPT="-rpltHO"
RSYNCOPT="$RSYNCOPT --delete-after"
[ $# -eq 0 ] || RSYNCOPT="$RSYNCOPT $@"

if [ -s "$BASE/exclude.txt" ]; then
       RSYNCOPT="$RSYNCOPT --exclude-from $BASE/exclude.txt --exclude exclude.txt"
fi

# find rsync
find_rsync() {
	local x= y=
	for x in /usr/local /usr ''; do
		for y in /sbin /bin; do
			if [ -x "$x$y/rsync" ]; then
				echo "$x$y/rsync"
				return
			fi
		done
	done
}

[ -x "${RSYNC:-}" ] || RSYNC="$(find_rsync)"

case "$RSYNCOPT" in
*-v*|*-i*)
	echo "Syncing with OpenSDE mirror ($RSYNCOPT)..."
	;;
esac

lkfile="$BASE/.lock"

if ln -s "${0##*/}" "$lkfile"; then
	trap "rm -f '$lkfile'" EXIT
	${RSYNC:-rsync} $RSYNCOPT ${RSYNC_OPENSDE_LOCATION:-rsync://dl.opensde.net/opensde-mirror} $BASE/
else
	echo "WARNING: $BASE is locked, aborting."
	exit 1
fi
