#!/bin/sh
#
# get-one-zone: runs nsdxfer for *one* zone
#
# Copyright (c) 2001-2004, NLnet Labs. All rights reserved.
#
# See LICENSE for the license.
#
#

# Optional configuration file for nsdc
configfile="/usr/local/nsd/etc/nsdc.conf"

#
# Default values in absense of ${configfile} (Usually ``/etc/nsd/nsdc.conf'')
#
prefix="/usr/local/nsd"
exec_prefix="/usr/local/nsd"

sbindir="/usr/local/nsd/sbin"
#zonesdir="/usr/local/nsd/zones"
zonesdir="/usr/local/nsd/zones/bidon"
flags=""
dbfile="/usr/local/nsd/var/nsd.db"
zonesfile="/usr/local/nsd/etc/nsd.zones"
#keysdir="/usr/local/nsd/etc/keys"
keysdir="/home/bortzmeyer/tmp/keys"
notify="/usr/local/nsd/sbin/nsd-notify"
nsdxfer="/usr/local/nsd/sbin/nsd-xfer"
pidfile="/var/run/nsd.pid"

ZONEC_VERBOSE=-v
NSD_XFER_VERBOSE=-v

#
# Read in configuration file if any
#
if [ -f ${configfile} ]
then
	. ${configfile}
fi

if [ "$3" = "" ]
then
     echo "Usage: $0 zone filename masters"
     exit 1
fi
zone=$1
file=$2
masters=$3

#
# You sure heard this many times before: NO USER SERVICEABLE PARTS BELOW
#
if [ ! -x "${nsdxfer}" ]
    then
    echo "${nsdxfer} program is not available, aborting..."
    exit 1
fi


# now get the serial number
serial_opt=''
if [ -e ${zonesdir}/$file ]; then
    serial=`awk '/.*IN[ \t]+SOA.*\($/ { getline; print $1; exit }' ${zonesdir}/$file`
    serial_opt="-s $serial"
fi

# take care of tsig info file if any
# See bug #91 - move to ${zone} but be backward
# compatible
unset tsiginfoarg
if [ -f "${keysdir}/${masters}.tsiginfo" ]
    then
    ln "${keysdir}/${masters}.tsiginfo" "${keysdir}/${masters}.tsiginfo.$$"
    tsiginfoarg="-T ${keysdir}/${masters}.tsiginfo.$$"
else 
    if [ -f "${keysdir}/${zone}.tsiginfo" ]
	then
	# the new way of doing things
	ln "${keysdir}/${zone}.tsiginfo" "${keysdir}/${zone}.tsiginfo.$$"
	tsiginfoarg="-T ${keysdir}/${zone}.tsiginfo.$$"
    fi
fi

# AXFR to a temp file $file.axfr
$nsdxfer ${NSDXFER_VERBOSE} -z $zone -f ${zonesdir}/$file.axfr ${tsiginfoarg} $serial_opt $masters
if [ $? -eq 1 ]
then
    if [ -f ${zonesdir}/$file.axfr ]
    then
	# axfr succeeded
	# test compile the zone to see what happens
	${sbindir}/zonec -o ${zone} -f ${zonesdir}/$file.axfr.db - < ${zonesdir}/$file.axfr 2>/dev/null
	if [ $? -eq 1 ]
	then
	    echo "Warning: AXFR of $zone did not compile"
	    rm -f ${zonesdir}/$file.axfr
	else
	    # we succeed
	    mv -f ${zonesdir}/$file.axfr ${zonesdir}/$file
	fi
	rm -f ${zonesdir}/$file.axfr.db
    else
	echo "Warning: AXFR for $zone failed"
    fi
fi

# clean up
rm -f -- "${keysdir}"/*.tsiginfo.*

