#!/bin/bash
#< Wrapper around named-checkconf to check named.conf files and mail on error

BASENAME="/bin/basename"
ECHO="/bin/echo"
MAILX="/usr/bin/mailx"
NAMED_CHECKCONF="/usr/local/sbin/named-checkconf"
RM="/bin/rm"

MAILTO="you@there.com"
MAILSUBJECT="Errors found in BIND configuration"
TMPFILE="/tmp/named-checkconf.$$"
THISPROG=$( ${BASENAME} $0 )

trap 'cleanup; exit 1' 1 2 3 15

function print_usage {
   {
      ${ECHO} "Usage: ${THISPROG} <conf_file>"
   } >&2
}

function print_error {
   ${ECHO} "Error: $@" >&2
}

function check_file_exists {
   # Check that file exists and is a regular file
   if [ ! -f "$1" ]; then
      print_error "Cannot open configuration file" && exit 1
   fi 
}

function check_named_checkconf {
   if [ ! -x "${NAMED_CHECKCONF}" ]; then
      print_error "Cannot executre named-checkconf" && exit 1
   fi
}

function check_named_conf {
   ${NAMED_CHECKCONF} ${CONF_FILE} >${TMPFILE} 2>&1
   if [ "$?" -ne "0" ]; then
      ${MAILX} -s "${MAILSUBJECT}" ${MAILTO} < ${TMPFILE}
      cleanup
      exit 2
   fi
}

function cleanup {
   ${RM} -f ${TMPFILE}
}

if [ "$#" -ne "1" ]; then
   print_usage && exit 1 
fi

CONF_FILE=$1

check_file_exists ${CONF_FILE}
check_named_checkconf
check_named_conf
cleanup

exit 0