#!/usr/bin/perl

use strict;

# Set files to use, change these to suit your needs
my $oldstatfile = "/tmp/dns-oldie.txt";
my $newstatfile = "/var/cache/bind/named.stats";

# Obtain old DNS stats from stored file
open(OLDF, "$oldstatfile");
my @raw_data = ;
close(OLDF);

my $oldsuccess = @raw_data[0] || 0;
my $oldfailure = @raw_data[1] || 0;

chomp($oldsuccess);
chomp($oldfailure);

# Get new data from file, first clean the stats file and dump new
system("cat /dev/null > $newstatfile");
system("/usr/sbin/rndc stats");
open(NEWF, "$newstatfile");
my @dns_data = ;
close(NEWF);

my $newsuccess = 0;
my $newfailure = 0;
my $line;

foreach $line (@dns_data) {
    if (($line =~ /([0-9]*) QUERY/)) {
        $newsuccess = $1;
    }

    if (($line =~ /([0-9]*) other query failures/)) {
        $newfailure = $1;
    }
}

# Calculate difference between old and new. Divide by 5 to get per minute
my $diffsuccess = ($newsuccess - $oldsuccess) / 5;
my $difffailure = ($newfailure - $oldfailure) / 5;

# Store new data
open(OLDF, ">$oldstatfile");
print(OLDF "$newsuccess\n$newfailure");
close(OLDF);

# Print difference
print("$diffsuccess \n$difffailure \n");