# Register routine with plugin registery
$DATAFUNCS{'rrd_ping'} = \&data_rrd_ping;

# Take the Ping status message and create rrd databases for interesting
# stats.

# RRA to be created for each RRD
# "daily" 5min avg last 48hr
# "weekly" 30min avg last 12days
# "monthly 2hr avg last 48days
# "yearly" 24hr avg last 576days
$RRAS = "RRA:AVERAGE:0.5:1:576 RRA:AVERAGE:0.5:6:576 RRA:AVERAGE:0.5:24:576 " . 
        "RRA:AVERAGE:0.5:288:576";

$RRDTOOL = "/usr/local/rrdtool/bin/rrdtool";
$RRDDIR  = "/home/spong/var/rrd";

sub data_rrd_ping {
   my( $host, $service, $color, $start, $time, $sum, $message ) = @_;

   if ($service ne 'ping' ) { return; }
   $time = time;
   my( $line, $rawfs, $used, $pct, $name, %namemap, $target );

   &main::save_data('>', "$RRDDIR/$host/.rrd-ping", "");

   my ($min) = undef;
   my ($avg) = undef;
   my ($max) = undef;

   # Bugger, different versions of MySQL have different ways of doing this...
   if ( $message =~ /max = ([.0-9]+)\/([.0-9]+)\/([.0-9]+) (\w+)/ ) {
     my ($mult) = 1;
     $mult = 0.001 if $4 eq 'ms';

     $min = $1 * $mult;
     $avg = $2 * $mult;
     $max = $3 * $mult;
   }
   
   if(defined $min && defined $avg && defined $max) {   
      # If .rrd file not found, built it
      if ( ! -f "$RRDDIR/$host/ping-times.rrd" ) {
        &debug("$RRDDIR/$host/ping-times.rrd not found creating it",4);
        {  local $SIG{'PIPE'} = 'IGNORE';
           local $SIG{'CHLD'} = 'IGNORE';

           eval {
              system "$RRDTOOL create $RRDDIR/$host/ping-times.rrd " . 
                     "DS:min:GAUGE:600:0:100 DS:avg:GAUGE:600:0:U " .
                     "DS:max:GAUGE:600:0:U $RRAS";
           };
         }
         if (@?) { &error("Error: rrdtool create: $@"); }
      }

      # Update the .rrd file
      &debug("Updating $host ping rrd file",4);
      {  local $SIG{'PIPE'} = 'IGNORE';
         local $SIG{'CHLD'} = 'IGNORE';
         system "$RRDTOOL update $RRDDIR/$host/ping-times.rrd " .
                "$time:$min:$avg:$max";
         if ($@) { &error("Error: rrdtool update: $@"); }
      }
   } else {
     &debug("Type mysql true but not parseable",4);
   }
}

# I'm include perl code, I need this line.
1;

