#!/usr/local/bin/perl
#
# updserial.pl 0.0.2 - Updates the serialnumber in one or more zonefiles
# Author: Christian Birchinger <christian.birchinger@cablecom.ch>
#
# Usage: updserial.pl [-d] <domain.ch> [<domain2.ch> <domain3.ch> <...]
#
#        -d   Dummy mode (Don't write any files
#

require 5.002;
use Getopt::Std;

getopts('vd');

if ( $opt_d ) {
	$testmode=1;
}

if ( $opt_v ) {          
        $verbosemode=1;
}

if (! $ARGV[0] ) {
	($basename = $0) =~ s/.*\///;
	print "Usage: $basename [-d] <domain.ch> [<domain2.ch> <domain3.ch> <...]\n";
}	

foreach $filename (@ARGV) {
  print "Updating $filename...\n";
  open (FILE, "$filename") or die "ERROR: Can't open $filename";
	$file = join '',<FILE>;
  close FILE;

	($curser) = $file =~ /.+\(\s*(\d*)/;
	$serial = getserial();

	if ( substr($curser,0,8) == substr($serial,0,8) ) {
		print "Same day, increasing counter...\n";
		$serial = $curser + 1;
		if ( length($serial) > 10 ) { die "ERROR: Serial string too long ... ABORTING" }
	}
	
	$file =~ s/(.+\(\s*)\d*/$1$serial/;
	if ($verbosemode) {
		print "-------------------------------------------------------------\n";
		print $file;
		print "-------------------------------------------------------------\n";
	}

	if (! $testmode) {
		print "Writing file $filename\n";
		open (FILE,">$filename") or die "ERROR: Can't overwrite $filename";
		print FILE "$file";
		close FILE;
	}

}

# -[ returns a valid serialnumber ]--------------------------------------------------
sub getserial {
	my ($mday,$mon,$year,$serialnum);
	($mday,$mon,$year) = (localtime)[3..5];
	$mon++;
	$year = $year + 1900;
	if (length($mon) eq 1) {$mon = "0" . "$mon"};
	if (length($mday) eq 1) {$mday = "0" . "$mday"};
	$serialnum = "$year" . "$mon" . "$mday" . "01"; 
	return $serialnum;
}
# -----------------------------------------------------------------------------------