#!/bin/sh
#
# Shuffle nameservers listed based on the query times, if enabled in
# resolv.conf. Bare in mind the special syntax.
#
# Rick van der Zwet <info@rickvanderzwet.nl>
#

# ``Random'' sleep between 0 and 30 minutes to avoid ``slamming'' on the DNS door
if [ "$1" = "cron" ]; then
  sleep `expr $$ % 30`
fi

TAG='^# TAG: DYNAMIC LIST$'

TDIR=`mktemp -d -t $(basename $0)`
DYNLIST=$TDIR/dynlist
RESULTLIST=$TDIR/resultlist
NEWRESOLV=$TDIR/resolv.conf.new

# Get enabled DYNAMIC LIST nameservers
sed "1,/$TAG/d" /etc/resolv.conf > $DYNLIST
NAMESERVERS=`awk '/^nameserver/ {print $2}' $DYNLIST`

# Only do something if we have dynamic nameservers
if [ -n "$NAMESERVERS" ]; then
  # Find query times
  for NAMESERVER in $NAMESERVERS; do 
    # Strict checking to avoid buggy links to return decent results.
    QUERY_TIME=`dig +time=1 +tries=1 SOA wleiden.net @$NAMESERVER | awk '/Query time:/ {print $4}'`
    # Failed to complete succesfully
    [ -z "$QUERY_TIME" ] && QUERY_TIME=9999
    echo "$QUERY_TIME $NAMESERVER" >> $RESULTLIST
  done
  
  # Get the header part 
  sed -n "1,/$TAG/p" /etc/resolv.conf > $NEWRESOLV
  
  # Output sorted list
  NAMESERVERS=`sort -n $RESULTLIST | awk '{print $2}'`
  for NAMESERVER in $NAMESERVERS; do
    grep '\b'$NAMESERVER'\b' $DYNLIST >> $NEWRESOLV
  done
  
  cp $NEWRESOLV /etc/resolv.conf
fi 

# Cleanup before going home
rm -Rf $TDIR
