#!/bin/sh

if [ -z "$1" ]; then
  echo
  echo "Usage: `basename $0` filename"
  echo
  exit
fi

filename="$1"

if [ ! -f "$filename" ]; then
  echo
  echo "File $filename not found"
  echo
  exit 1
fi

if [ -z "$EDITOR" ]; then
  EDITOR="/usr/bin/vi"
fi

oldmd5="`md5 -q $filename`"
oldserial="`cat $filename | perl -e '$_ = join "" ,<> ; print if ($_) = /.+\(\s*(\d*)/m'`"

eval $EDITOR "$filename"

newmd5="`md5 -q $filename`"
newserial="`cat $filename | perl -e '$_ = join "" ,<> ; print if ($_) = /.+\(\s*(\d*)/m'`"

if [ "$oldmd5" = "$newmd5" ]; then
  echo 
  echo "File $filename was not modified."
  echo 
  exit
fi

if [ -z "$oldserial" -o -z "$newserial" ]; then
  echo
  echo "PANIC: Unable to get Serial from zonefiles. ABORTING!"
  echo
fi

if [ "$oldserial" = "$newserial" ]; then
  echo "File $filename was modified but serial not changed. Updating serial now."
  updserial "$filename"
fi
