#!/bin/sh
#Author : Stéphane BORTZMEYER http://www.bortzmeyer.org/recuperer-zone-dns.html
#Modification : Richard DEMONGEOT http://www.demongeot.biz

#Licence : GPL v2. see http://www.fsf.org/licensing/licenses/info/GPLv2.html for more options.

# Tries to download a DNS zone file by testing one after the other all
# its authoritative name servers.

# Where to put the downloaded zone
set -x
basedir=/tmp

if [ -z "$1" ]; then
   echo "Usage: $0 zone" > /dev/stderr
   exit 1
fi

zone=$1
nameservers=`dig +short NS ${zone}` # TODO: it may fail...
tmp=`mktemp`
for ns in $nameservers; do
    dig @${ns} AXFR $zone > $tmp 2>&1
    # Testing the return code is useless, dig always return zero :-(
    # Add "communications error to" in the egrep list. RD
    if ! egrep "communications error to|Transfer failed|connection timed out|Name or service not known|connection refused|network unreachable|host unreachable"\
            $tmp > /dev/null; then
    filename=${basedir}/${zone}.db
    mv $tmp $filename
    echo "Got $zone from $ns, saved in $filename"
    exit 0
    fi
done
echo "No willing nameservers from which to transfer $zone" > /dev/stderr
exit 2

