#!/bin/sh
# $Id: bind-forwarders,v 1.8 2004/01/09 12:05:50 andrew Exp $
#
# by Andrew McMillan, Catalyst IT Ltd, (c) 2002 licensed
# for use under the GPL version 2
#
# 2003-12-09 Chris Halls  Does not run if resolvconf is installed
#
# usage:
# bind-forwarders <IP address>
#

if [ -x /sbin/resolvconf ] ;then
    logger -p user.info -t whereami -i "bind-forwarders ignored, resolvconf is installed"
    exit 0
fi

# Support bind or bind9 as init script
BINDINIT=/etc/init.d/bind
if [ -x "${BINDINIT}9" ]; then
  BINDINIT=${BINDINIT}9
  BINDPID="`cat /var/run/bind/run/named.pid`"
else
  BINDPID="`cat /var/run/named.pid`"
fi

# Possibly this is different for bind9 too?
FILENAME=/etc/bind/named.conf

if [ ! -e $FILENAME ] ; then
  logger -p user.warning -t whereami -i "Bind configuration named.conf missing!"
  cp $FILENAME.last $FILENAME
  if [ ! -e $FILENAME ] ; then
    logger -p user.error -t whereami -i "Really stuffed - can't copy from backup named.conf!"
    exit 1 
  fi
fi

# Use the first nameserver in /etc/resolv.conf if we didn't
# get told one on the command line.
if [ -z "$1" ]; then
  PRIMARY=`tr -s ' ' </etc/resolv.conf | grep "^nameserver " | cut -f2 -d' ' | head -1`
  if [ -z "$PRIMARY" ]; then
    logger -p user.error -t whereami -i "Can't extract current nameserver from resolv.conf!"
    exit 1
  fi
else
  PRIMARY=$1
fi

logger -p user.info -t whereami -i "Setting forwarder to $PRIMARY"
sed -e "s/\([  ]*\)[0-9.]*\([;].*bind-forwarders\)/\1$PRIMARY\2/" <$FILENAME >$FILENAME.tmp

#
if [ -e $FILENAME.tmp ] ; then
  mv $FILENAME $FILENAME.last
  cp $FILENAME.tmp $FILENAME
  chmod --reference=$FILENAME $FILENAME.tmp
  chown --reference=$FILENAME $FILENAME.tmp
  # Enforce readability by owner as minimum
  chmod u+r $FILENAME
else
  logger -p user.error -t whereami -i "Error handling named.conf changes!"
  exit 1 
fi

# Look for the named.conf file again.
if [ ! -e $FILENAME ] ; then
  logger -p user.error -t whereami -i "Wha..? named.conf gone missing!"
  exit 1
fi

# Test to see if bind is already running (just reload it) or needs to be started
BIND_RUNNING="`find /proc -type d -maxdepth 1 -name ${BINDPID}`"
if [ "$BIND_RUNNING" = "" ] ; then
  logger -p user.warning -t whereami -i "Nameserver not running - starting it."
  ${BINDINIT} start
else
  logger -p user.notice -t whereami -i "Reloading nameserver."
  ${BINDINIT} reload
fi

if [ ! -e $FILENAME ] ; then
  logger -p user.error -t whereami -i "Wha..? named.conf gone missing after restarting bind!"
  exit 1
fi

