#!/bin/bash

listfile=conf/ubuntu_mirrors
wd=tmpdir.$RANDOM
mkdir -p $wd || exit 1


wget -q -O- 'https://wiki.ubuntu.com/Mirrors?action=show&redirect=Archive' 'https://launchpad.net/ubuntu/+archivemirrors' | tr -d ' ' | tr -d '\t' | sed -e 's,",\n,g' | grep ^http | sort -u > $wd/list

ubuntu_stamp=$(head -n1 $listfile | grep '^#' | cut -c2-38)
stamp=$(md5sum $wd/list | cut -f1 -d' ')
if test "$stamp" != "$ubuntu_stamp" ; then

   echo Needs to update Ubuntu lists, probing into $wd'/url.*' ...

   a=0
   for x in `cat $wd/list` ; do
      a=$(( $a + 1 ))
      wget -q -t 1 -O- --timeout=10 $x/dists/ | grep -q 'updates\|security\|backports\|feisty\|gutsy' && echo $x > $wd/url.$a &
      sleep 0.2
   done

   wait

   echo '#'$stamp > $listfile
   cat $wd/url.* | sed -e 's,$,/,;s,//$,/,' >> $listfile

   echo $listfile created.

fi

wget -q -O $wd/deb 'http://cvs.debian.org/*checkout*/webwml/english/mirror/Mirrors.masterlist?rev=HEAD&cvsroot=webwml&content-type=text/plain'
stamp=$(md5sum $wd/deb | cut -f1 -d' ')
debian_stamp=$(zcat conf/deb_mirrors.gz | md5sum | cut -f1 -d' ')

if test "$stamp" != "$debian_stamp" ; then
   echo News on Debian lists found, updating...
   # FIXME: could optimize that and store only the relevant fields and the checksum, but who cares...
   gzip -9 < $wd/deb > conf/deb_mirrors.gz
   echo conf/deb_mirrors.gz created.
fi
