#!/bin/sh

source /etc/conf.d/eworm-repo
source /usr/lib/eworm/nice

function help() {
	echo "usage: ${0} [OPTIONS]"
	echo
	echo "where OPTIONS are:"
	echo " -4  use IPv4"
	echo " -6  use IPv6"
	echo " -h  show this help"
	echo " -r  sync reverse (update local from remote)"
}

REVERSE=0
RSYNC=(rsync --archive --verbose --stats --info=progress2 --human-readable --human-readable)
IPV=0

while getopts "hr46" opt; do
	case ${opt} in
		h)
			help
			exit 0
			;;
		r)
			REVERSE=1
			;;
		4)
			IPV=4
			;;
		6)
			IPV=6
			;;
	esac
done

exec 9> /tmp/.$(basename ${0}).lock

if ! flock -x -n 9; then
	echo "Warning: Sync is still running, not syncing." >&2
	touch /tmp/.$(basename ${0}).sync
	exit 0
fi

if [ -s "${REPODIR}/.exclude" ]; then
	RSYNC+=("--exclude-from=${REPODIR}/.exclude")
fi

if [ ${IPV} -gt 0 ]; then
	RSYNC+=(-${IPV})
elif fping -6 -q "${REPOSERVHOST%:*}"; then
	RSYNC+=(-6)
elif fping -4 -q "${REPOSERVHOST%:*}"; then
	RSYNC+=(-4)
else
	echo "External repo server ${REPOSERVHOST} not accessible, not syncing."
	exit 1
fi

# create the file once
# if the file exists for more than one iteration another process created it while we had the lock
touch /tmp/.$(basename ${0}).sync

while [ -f /tmp/.$(basename ${0}).sync ]; do
	rm -f /tmp/.$(basename ${0}).sync
	if [ "${REVERSE}" = 1 ]; then
		RSYNC_PASSWORD="${REPOSERVPASS}" "${RSYNC[@]}" --update \
			${EXCLUDE} --exclude=${REPONAME}.{db,files}.tar.gz.old{,.sig} \
			"rsync://${REPOSERVUSER}@${REPOSERVHOST}/${REPOSERVPATH}/" "${REPODIR}/"
	else
		RSYNC_PASSWORD="${REPOSERVPASS}" "${RSYNC[@]}" --delete-before --delete-excluded \
			${EXCLUDE} --exclude=${REPONAME}.{db,files}.tar.gz.old{,.sig} \
			"${REPODIR}/" "rsync://${REPOSERVUSER}@${REPOSERVHOST}/${REPOSERVPATH}/"
	fi
done

