#!/bin/sh
# Copyright 1999-2003 Gentoo Technologies, Inc.
# Distributed under the terms of the GNU General Public License v2
# $Header: /home/cvsroot/gentoo-src/portage/bin/emerge-webrsync,v 1.3 2003/02/23 23:10:03 alain Exp $
# Author: Karl Trygve Kalleberg <karltk@gentoo.org>
# Rewritten from the old, Perl-based emerge-webrsync script

GENTOO_MIRRORS="$(/usr/lib/portage/bin/portageq gentoo_mirrors)"
PORTDIR="$(/usr/lib/portage/bin/portageq portdir)"
syncpath="/var/tmp/emerge-webrsync"

if [ ! -d $syncpath ] ; then
	mkdir -p $syncpath
fi

cd $syncpath

found=0
attempts=0
download=1
if [ "$1" == "-v" ] ; then
	wgetops=
else	
	wgetops=-q
fi

if [ "$1" == "-n" ] ; then
	download=0
fi

sync_local() {
	echo Syncing local tree...
	tar jxf $file
	rm -f $file
	# Make sure user and group file ownership is root
	chown -R root:root portage
	cd portage
	rsync -av --progress --stats --delete --delete-after \
	--exclude='distfiles/*' --exclude='packages/*' . ${PORTDIR%%/}
	cd ..
	rm -rf portage
}

echo "Fetching most recent snapshot"

while (( $attempts <  40 )) ; do

	day=`date -d "-$attempts day" +"%d"`
	month=`date -d "-$attempts day" +"%m"`
	year=`date -d "-$attempts day" +"%Y"`

	file="portage-${year}${month}${day}.tar.bz2"

	if [ -f $file ] && [ $download == 0 ] ; then
		sync_local
		exit 0
	fi

	for i in $GENTOO_MIRRORS ; do 
		url="${i}/snapshots/$file"
		rm -f $file
		
		if (wget $wgetops $url) && [ -s $file ] ; then
			sync_local
			echo
			echo " *** Completed websync, please now perform a normal rsync if possible."
			echo "     Update is current as of the of YYMMDD: ${year}${month}${day}"
			echo
			exit 0
		fi
	done
	attempts=$[attempts+1]
done

rm -rf portage

exit 1
