#!/bin/sh

if [ -f "/var/run/mirror.pid" ]; then
	RUNPID=`cat /var/run/mirror.pid`
	if ps -p $RUNPID; then
		echo "Mirror is already running..."
		exit 1
	else
		echo "Mirror pid found but process dead, cleaning up"
	 rm -f /var/run/mirror.pid
	fi
else
	echo "No Mirror Process Detected"
fi
echo $$ > /var/run/mirror.pid

if [ ! -f /usr/sbin/fping ];then
	echo "fping not found,pls install fping ,http://download.fedora.redhat.com/pub/epel/5/i386/"
	exit 1
fi

rm -f index.html
wget -O index.html -c "http://www.centos.org/modules/tinycontent/index.php?id=13"
sed 's#</a>#</a>\n#g' index.html |sed 's#<a>#\n<a>\n#g' |sed 's#</td>#</td>\n#g' |sed 's#<td>#\n<td>\n#g' |sed 's#</tr>#</tr>\n#g'>a.html
grep "href='rsync://" a.html |awk -F"href='" '{print $2}' |awk -F"'>RSYNC" '{print $1}' >site.txt
cat site.txt|grep -v '::' |awk -F'/' '{print $3}' |egrep -v "(linux.mirrors.es.net|mirror.stanford.edu)" >site
cat site

echo 'fping -e -f site 2'
fping -e -f site 2>/dev/null |grep -v unreachable |sed 's/(/ /g' |awk -F' ' '{print $4,$1}' |sort -n |head -n 1 |awk -F' ' '{print $2}'>ok.txt
a=`cat ok.txt`
mirror=`grep $a site.txt |tail -n 1 |sed -e 's/\/$//g'`
echo "the fast site:  ""$mirror"
sleep 2

if [ ! -n "$mirror" ];then
	echo "site is zero"
	exit 1
fi

rm -f ok.txt site.txt a.html site index.html
  
echo "Mirror Starting ...................."

chown -R apache:apache /opt/web/mirrors.sohu.com/
/usr/bin/rsync -avvzH --delete-after --exclude-from=/opt/rsync.exclude $mirror /opt/web/mirrors.sohu.com/centos/ 

find /opt/web/mirrors.sohu.com/centos/ -name "ia64" |xargs rm -rf
find /opt/web/mirrors.sohu.com/centos/ -name "s390" |xargs rm -rf
find /opt/web/mirrors.sohu.com/centos/ -name "s390x" |xargs rm -rf
find /opt/web/mirrors.sohu.com/centos/ -name "alpha" |xargs rm -rf

rm -f /var/run/mirror.pid
chown -R apache:apache /opt/web/mirrors.sohu.com/centos/
