#!/bin/sh
# (C) Copyright 2004, Perry Lorier
#
# This script validates all the DNS zone files for obvious mistakes 
#
# It checks:
#  * The serial number is of the form yyyymmddxx where yyyymmdd is the same
#    as the modification date of the file.  This means you will notice if
#    you forgot to update the serial.
#
#  * if a word ends with "com" "net" "nz" "org" instead of "com." "net." 
#    etc, to warn if you forget a .
#
#  * If you don't have a $TTL line.
#
# You should probably also use
#  http://dnsreport.com/
# to check for issues with your domain.

function error() {
        if [ "$ERROR" != "$1" ]; then
                echo "In file: $1"
                ERROR=$1
        fi
        shift
        echo " $*"
}

function validate_zone() {
        # Only validate files
        if [ ! -f $1 ]; then
                return
        fi
        # Don't validate backups
        if echo $1 | grep -q "~"; then
                return
        fi
	# Check for $TTL somewhere in the file
        grep -q "^\$TTL" $1 || {
                error $1 "Missing \$TTL"
        }
	# Check for names sneding in .nz .com .org .net that don't have
	# a . after them.  (prevents mistakes like www.example.org.example.org)
        for i in nz com org net au int name info arpa; do
                grep -i "\.${i}[^\\.a-zA-Z]" $1 >/tmp/validate&& {
                        error $1 "Dangling ${i}? ($?) "
                        cat /tmp/validate
                }
        done
	# Try and find if the serial is of the form YYYYmmdd
        grep -q $(date -r $1 +'%Y%m%d') $1 || {
                error $1 "Serial does not match modification time"
        }
}

if [ $# = 0 ]; then
        for i in /etc/bind/zones/*; do
                validate_zone $i
        done
else
        for i in $*; do
                validate_zone $i
        done
fi

if [ -z "$ERROR" ]; then
        echo All zones validate ok
        exit 0;
else
        echo Errors were encountered
        exit 1;
fi