#!/bin/sh

if [ -r /etc/sisyphus-mirror/sisyphus-mirror.conf ]; then
		. /etc/sisyphus-mirror/sisyphus-mirror.conf
fi

if [ ! -d "$RSHOME" ]; then
	echo ""
	echo "Directory \"$RSHOME\" does not exists, creating..."
	echo ""
	echo "You may want edit now personal config file \"$RSHOME\"/config"
	echo "(if don't, please re-run this script)"
	echo ""
	mkdir -p "$RSHOME"; exit 1
fi

if [ -r "$RSHOME"/config ]; then
	. "$RSHOME"/config
fi

export RSYNC_PROXY
RSYNC_RSH=rsh
RSYNCARGS="$ARGS --timeout=$TMOUT1 --exclude-from=$EXCLUDE_FILE \
		--bwlimit=$SPEED --partial-dir=$PARTIAL"

for mirror in $LIST; do
	OK=""
	mirror_log=$(echo $mirror | tr "/" "_");
	LOG="$RSHOME"/rsync-$mirror_log.log
	LOCK="$RSHOME"/lock.$mirror_log
	FLAG="$DESTROOT"/$mirror/__SYNCING__
	date >> $LOG
	[ -f $LOCK ] && {
		ps auxww | grep "/bin/sh /usr/bin/sisyphus-mirror" | grep -v grep \
			| mail -s "sync: $mirror: lockfile $LOCK exists" "$MAINTAINER"
		echo "Lockfile $LOCK for $mirror exists, exiting" >> $LOG
		continue
	}
	trap "rm -f $LOCK; exit 1" INT
	touch $LOCK $FLAG

	for attempt in `seq 1 "$MAXATTEMPTS"`; do
		mkdir -p "$DESTROOT"/$mirror
		if [ "$INTERACTIVE" == 1 ]; then
			rsync $RSYNCARGS $* "$SRCROOT"/$mirror/ "$DESTROOT"/$mirror 2>&1 && {
			OK="1"
			break 
			}
		else
			rsync $RSYNCARGS $* "$SRCROOT"/$mirror/ "$DESTROOT"/$mirror >> $LOG 2>&1 && {
			OK="1"
			break
			}
		fi
		sleep "$TMOUT2"
	done
	[ -z "$OK" ] && {
		tail $LOG | mail -s "sync: $mirror trouble" "$MAINTAINER"
	} || {
		rm -f $FLAG
	}
	rm -f $LOCK
	date >> $LOG
done

nice symlinks -dr "$DESTROOT" >/dev/null
