#!/bin/bash
#< Check zone serials across multiple nameservers

AWK="/usr/bin/awk"
BASENAME="/bin/basename"
DIG="/usr/local/bin/dig"
ECHO="/bin/echo"
GREP="/usr/bin/grep"

DIGOPTS="+noadd +noauth +nostats +noquestion +nocomments +nocmd +time=2"
SERVERS="192.168.0.1 192.168.0.2"
THISPROG=$( ${BASENAME} $0 )

NAME=""
RECORDTYPE="soa"
VERBOSE=0

function print_usage {
   {
      ${ECHO} "Usage: ${THISPROG} [-h] -n <name>"
      ${ECHO} "       -n   Name, e.g. foo.com.au"
      ${ECHO} "       -h   Print this help messsage"
   } >&2
}

function check_args {
   if [ "${NAME}" = "" ]; then
      print_usage && exit 1  
   elif [ "${RECORDTYPE}" = "" ]; then
      print_usage && exit 1  
   fi
}

function perform_checks {
   for SERVER in ${SERVERS}; do
      DIGOUTPUT=$( ${DIG} ${DIGOPTS} ${RECORDTYPE} ${NAME} @${SERVER} 2>&1 )
      ${ECHO} "${DIGOUTPUT}" | ${AWK} '{print $7}' | ${GREP} '^[0-9]\{1,\}$' >/dev/null 2>&1
      if [ "$?" -eq "0" ]; then
         SERIAL=$( ${ECHO} "${DIGOUTPUT}" | ${AWK} '{print $7}' )
         ${ECHO} "Server: ${SERVER} Zone: ${NAME} Serial: ${SERIAL}"
      else
         ${ECHO} "Could not get serial for ${NAME}@${SERVER}" >&2
      fi
   done
}

while getopts ":hn:v" OPTION; do
  case ${OPTION} in
     "h")  print_usage && exit 0  ;;
     "n")  NAME="${OPTARG}"       ;;
     "v")  VERBOSE=1              ;;
     *  )  print_usage && exit 1  ;;
  esac
done

shift $(( ${OPTIND} - 1 ))

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

check_args
perform_checks

exit 0