#!/usr/bin/perl

#  Configure BIND to dump stats to /var/local/bind-stats; then
#  configure a crob job to call 'rndc stats' every 5 minutes or so to
#  regenerate the stats file and rename the previous stats file
#  to /var/local/bind-stats.prev
#
# Just strip the comment sign and leading space from the code below
# to use any of it :)
#
# bash# cat /etc/cron.d/bind-stats
# */10 * * * * root /usr/local/bin/bind9-genstats.sh >/dev/null 2>&1
#
# /etc/named.conf options to use to generate stats
# options {
#       zone-statistics yes;
#       statistics-file "/var/local/bind-stats";
# }
#
# Script to generate the stats from the cron job
#
# bash# cat /usr/local/bin/bind9-genstats.sh
# #!/bin/bash
#
# cat /var/local/bind-stats > /var/local/bind-stats.prev
# cat /dev/null > /var/local/bind-stats
# /usr/sbin/rndc stats
#
# exit 0

use strict;
my $current = '/var/local/bind-stats';
my $previous = '/var/local/bind-stats.prev';

my %cur = get_stats($current);
my %prev = get_stats($previous);

print join(' ',
           (map { sprintf "%s:%s", $_, ($cur{$_} - $prev{$_}); }
           (keys %cur)));

exit 0;

sub get_stats {

     my $file = shift;
  
     open(*FILE, "< $file") || die "Can't read from $file: $!\n";

     <FILE>;

     my %stats;

     for (my $i = 0; $i < 6; $i++) {
         my $line = <FILE>;
         chomp($line);
         my ($key, $value) = split(' ', $line);
         $stats{$key} = $value;
     }

     return %stats;
}
