#!/bin/bash
# apt-spy-updates-apt-proxy.conf : a tool for choosing the best 
# servers
# Copyright (C) 2008 Patrick ZANON (patrick.zanon@gmail.com)
#
# This tool is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.


MIRRORLIST=/tmp/`date +%Y.%m.%d-%H.%M.%S`-mirrorlist.txt
RANKEDLIST1=/tmp/`date +%Y.%m.%d-%H.%M.%S`-rankedlist1.txt
RANKEDLIST2=/tmp/`date +%Y.%m.%d-%H.%M.%S`-rankedlist2.txt

PROXYCONF=/etc/apt-proxy/apt-proxy-v2.conf
NEWPROXYCONF=/tmp/`date +%Y.%m.%d-%H.%M.%S`-apt-proxy-v2.conf


#
# Stop the daemon
#
/etc/init.d/apt-proxy stop

#
# New mirror list
# and clean from bad servers (workaround for Bug #457049)
#
apt-spy update
cat /var/lib/apt-spy/mirrors.txt | grep -v "  (" > ${MIRRORLIST}


#
# Find the most 6 most performing servers
# repeat the test miany times to get a reliable result
#
apt-spy -d lenny -a europe -m ${MIRRORLIST} -w ${RANKEDLIST1} -n 12
apt-spy -d lenny -a europe -m ${MIRRORLIST} -i ${RANKEDLIST1} -w ${RANKEDLIST12} -n 10
apt-spy -d lenny -a europe -m ${MIRRORLIST} -i ${RANKEDLIST2} -w ${RANKEDLIST11} -n 8
apt-spy -d lenny -a europe -m ${MIRRORLIST} -i ${RANKEDLIST1} -w ${RANKEDLIST12} -n 6
#apt-spy -d lenny -s by -m ${MIRRORLIST} -w ${RANKEDLIST2} -n 6


#
# Substitute the servers into the apt-proxy configuration
#
cat ${PROXYCONF} | awk 'BEGIN {f1=0} {if ($0 == "[debian]") f1=1; if (f1 == 1 && index($0, "backends =") != 0) exit; print } END { print }' > ${NEWPROXYCONF}
cat ${RANKEDLIST2} | awk -F : -- '{ printf "\tftp://%s%s\n", $1, $2 } END {printf "\n"}' >> ${NEWPROXYCONF}
cat ${PROXYCONF} | awk 'BEGIN {f1=0; f2=0} {if ($0 == "[debian]") f1=1; if (f1 == 1 && index($0, "min_refresh_delay =") != 0) f2=1; if (f2 == 1) print }' >> ${NEWPROXYCONF}

cp -f ${NEWPROXYCONF} ${PROXYCONF}


#
# Cleanup
#
rm ${MIRRORLIST}
rm ${RANKEDLIST1}
rm ${RANKEDLIST2}
rm ${NEWPROXYCONF}


#
# Start the daemon
#
/etc/init.d/apt-proxy start


