#! /bin/sh
set -e

cd /home/debian
HOSTNAME=debian.ludost.net
TO=/home/debian/public/debian

RSYNC_HOST=$1
RSYNC_DIR=debian/
. conf/excludes

#-----------------------------------------------------------------------------#

LOCK="${TO}/Archive-Update-in-Progress-${HOSTNAME}"

# Get in the right directory and set the umask to be group writable
# 
cd $HOME
umask 002

# Check to see if another sync is in progress
if lockfile -! -l 43200 -r 0 "$LOCK"; then
  echo ${HOSTNAME} is unable to start rsync, lock file exists
  exit 1
fi
# Note: on some non-Debian systems, trap doesn't accept "exit" as signal
# specification. If that's the case on your system, try using "0".
trap "rm -f $LOCK > /dev/null 2>&1" exit

set +e
#here's the principle:
# you rsync everything but Packeges & Packages.gz, no deleting
# than you rsync only Packages and Packages.gz
# and then you do a delete-ionly rsync

while ! rsync --recursive --links --hard-links --times --verbose \
	--timeout=300 $EXCLUDE \
	--exclude "Archive-Update-in-Progress-${HOSTNAME}" \
	--exclude "project/trace/${HOSTNAME}" \
	--exclude "*/Packages" \
	--exclude "*/Packages.gz" \
	$RSYNC_HOST::$RSYNC_DIR $TO ;
	do sleep 2;
done

while ! rsync --recursive --links --hard-links --times --verbose \
	--timeout=300 \
	--exclude "*" \
	--include "*/Packages" \
	--include "*/Packages.gz" \
	$RSYNC_HOST::$RSYNC_DIR $TO;
	do sleep 2;
done

while ! rsync --recursive --links --hard-links --times --verbose --compress \
     --delete --delete-excluded --delete-after \
     --exclude "Archive-Update-in-Progress-${HOSTNAME}" \
     --exclude "project/trace/${HOSTNAME}" \
     --max-delete=200 \
     --timeout=300 \
     $EXCLUDE \
     $RSYNC_HOST::$RSYNC_DIR $TO ; do
     	sleep 2;
done
date -u > "${TO}/project/trace/${HOSTNAME}"

#savelog log/rsync.log > /dev/null 2>&1
