#!/bin/sh
## This is a repaired version of a script offered in 2009 by a poster named 
## 'clinty' to forums.freebsd.org .  Accordingly, copyright is his/hers, 
## but the author never stated any licence terms.

# vars
#ZONEPATH=/etc/bind

# check args
if [ ! $# -eq 1 ]; then
        echo "Usage $0 domain.tld"
        exit 1
fi

# read zonefile from cmd
ZONE=${ZONEPATH}/${1}

# check the file
if [ ! -f ${ZONE} ]; then
        echo "Error: zone does not exist"
        exit 1
fi

# get serial number
SERIAL=$(grep -e "2[0-9]\{3\}[0-1]\{1\}[0-9]\{1\}[0-3]\{1\}[0-9]\{1\}[0-9]\{2\}" ${ZONE} | awk '{print $1}')

# get serial number's date and number
SERIAL_DATE=$(echo ${SERIAL} | cut -b 1-8)
SERIAL_NUMBER=$(echo ${SERIAL} | cut -b 9-10)

# get today's date in same style
DATE_TODAY=$(date +%Y%m%d)

# compare date and serial date
if [ "${SERIAL_DATE}" = "${DATE_TODAY}" ]
then
        # if equal, just add 1
        # if equal and number equal 99, do not change
        if [ ${SERIAL_NUMBER} -ge 99 ]; then
                NEWSERIAL=${SERIAL}
        else
                # increment serial number
                NEWSERIAL_NUMBER=$(expr $SERIAL_NUMBER + 1)
                # if < 10, add a 0 to have 2 digits
                if [ ${NEWSERIAL_NUMBER} -le 9 ]; then
                        NEWSERIAL_NUMBER="0"${NEWSERIAL_NUMBER}
                fi
                # construct new serial
                NEWSERIAL=${SERIAL_DATE}${NEWSERIAL_NUMBER}
        fi
else
        # if not equal, make a new one and add 00
        NEWSERIAL=$(echo ${DATE_TODAY}"00")
fi

# write the new serial
sed -i -e "s/${SERIAL}/${NEWSERIAL}/g" ${ZONE}

#ok
exit 0
