# Register routine with plugin registery
$DATAFUNCS{'rrd_realserver'} = \&data_rrd_realserver;

use Data::Dumper;

# Take the RealServer status messages and create rrd databases for each of 
# the encoders.

# 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_realserver {
   my( $host, $service, $color, $start, $time, $sum, $message ) = @_;

   if ($service ne 'realserver' ) { return; }

   my( $line, $name );

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

   foreach my $line ( split(/\n/,$message) ) {
      if ( $line =~ /\s*(\w+)\s*[.0-9]+\s*(.*?)\s*$/ ) {
         my ($type) = $1;
         my ($words) = $2;

         if ($type eq 'Player') {
            $count{$words} = 0
               if ! defined $count{$words};
            $count{$words}++;
          } elsif ($type eq 'Encoder') {
            if ($words =~ /(.*?)\s*\((\w+)\)/) {
               $map{$2} = $1;
           }
         }
      }
    }
            
  # If there are no players currently connected for any live streams we'd
  # better set the count to 0.
  foreach my $stream (keys %map) {
    $count{$stream} = 0
      if ! defined $count{$stream};
  }

  foreach my $stream ( keys %count ) {
    # If .rrd file not found, build it
    if ( ! -f "$RRDDIR/$host/realserver-$stream.rrd" ) {
      &debug("$RRDDIR/$host/realserver-$stream.rrd not found creating it",4);
      { local $SIG{'PIPE'} = 'IGNORE';
        local $SIG{'CHLD'} = 'IGNORE';

        eval {
          system "$RRDTOOL create $RRDDIR/$host/realserver-$stream.rrd " . 
                 "DS:players:GAUGE:600:0:U $RRAS";
        };
      }
      if (@?) { &error("Error: rrdtool create: $@"); }
    }

    # Update the .rrd file
    &debug("Updating $host $name rrd file",4);
    { local $SIG{'PIPE'} = 'IGNORE';
      local $SIG{'CHLD'} = 'IGNORE';

      system "$RRDTOOL update $RRDDIR/$host/realserver-$stream.rrd " .
             "$time:$count{$stream}";
      if ($@) { &error("Error: rrdtool update: $@"); }
    }
  }

  $line = "";
  while(($k,$v) = (each %map)) {
    $line .= "$k:$v\n";
  }

  # Write the file name to mount map to 
  &main::save_data('>', "$RRDDIR/$host/realserver-stream-map", $line );

}

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

