#!/bin/sh
#
# Copyright 2004 (c) Michael Shigorin <mike@osdn.org.ua>
# Copyright 2004-2005 (c) Ivan Fedorov <ns@altlinux.ru>
# script for snapshotting ALT Linux Sisyphus locally.
#
#

# mirror/site-specific
SRC="rsync.altlinux.ru::ALTLinux/Sisyphus/"
BASEDIR="/var/ftp/pub/distributions/ALTLinux/Sisyphus-daily/"

########################################
###SRC="sisyphus.irkutsk.ru::ALTLinux/Sisyphus/"
###BASEDIR="/var/tmp/SIS/Sisyphus-daily/"
########################################

# retry params
MAXCOUNT=10
TIMEOUT=60

# shouldn't need to be changed
DATE=`date +%Y%m%d`
DATE_P=`date +%Y/%m/%d`
DATE_Y=`date +%Y`
DATE_M=`date +%m`

########################################
###DATE=`date +%Y%m%d -d 1day`
###DATE_P=`date +%Y/%m/%d -d 1day`
########################################

LOGDIR="$BASEDIR/../log/"
LOGFILE="$LOGDIR/Sisyphus_$DATE.log"
DEST="$BASEDIR/.syncing"

RSYNCARGS="-vaz --stats --delete-after"

unset OK

# init env
mkdir -p "$BASEDIR/$DATE_Y/$DATE_M" "$LOGDIR"
cd "$BASEDIR" || exit 1

# create hardlinked copy or init dir; order critical
LAST=`ls -d1 20??/??/?? 2>/dev/null | sort | tail -1`

########################################
###LAST="2005/01/19"
########################################

rm -rf "$DEST"
mkdir -p "$DEST"

[ ! -d "$LAST" ] && {
  echo "Can't create $DEST" >> "$LOGFILE"
  exit 1
}

for attempt in `seq 1 $MAXCOUNT`; do 
	rsync $RSYNCARGS "$SRC" "$DEST" --link-dest "$BASEDIR/$LAST" 2>&1 >> "$LOGFILE" && {
		OK="yes"
		break
	}
	sleep "$TIMEOUT"
done

[ -z "$OK" ] && {
  echo "Syncing problems" | tee -a "$LOGFILE"
  exit 1
}

[ ! -d "$BASEDIR/$DATE_P" ] && {
	mv "$DEST" "$DATE_P"
	# fix symlink
	rm -f $BASEDIR/../Sisyphus
	ln -s Sisyphus-daily/"$DATE_P" $BASEDIR/../Sisyphus
} || {
	echo "$DATE_P already exists" | tee -a "$LOGFILE"
	mv "$DEST" "$DATE_P.new"
	exit 2
}

echo "** $DATE sync OK" >> "$LOGFILE"
