#!/usr/bin/perl

use strict;
use warnings;

use RRDs '1.3';

#################################################################

my $bad = 'bad.rrd';
my $good = 'good.rrd';
my $rows = 40;
my $step = 10;

my $now = time();
my $start = $now - ($rows+1)*$step;
$start -= $start % $step;

for my $file ($bad, $good)
{
    unlink($file);
    RRDs::create($file,
                 '--start' => $start,
                 '--step'  => $step,
                 'DS:now:GAUGE:500:0:U',
                 "RRA:AVERAGE:0.5:1:$rows",
                 "RRA:MIN:0.5:6:$rows",
             );

    $_ and die $_ for (RRDs::error);
}

my @updates =
    map { "$_:$_" }
    grep { $_ % $step == 0 }
    $start+$step .. $now+$step*8;

###################################
## illustrate the difference.

RRDs::update($bad, @updates);
$_ and die $_ for (RRDs::error);

for my $up (@updates)
{
    RRDs::update($good, $up);
}

###################################
## just where to look

my $info = RRDs::info($bad);
my $lastup = $info->{last_update};

my $empty = $info->{'rra[0].rows'} - $info->{'rra[0].cur_row'} - 1;
my $empty_time = $lastup - $info->{'rra[0].cur_row'} * $step;

print "rra[0] row $empty for time $empty_time is NaN, but it shouldn't be ...\n";

###################################

my $cf_step = $step * $info->{'rra[1].pdp_per_row'};

my $corrupt = $info->{'rra[1].rows'} - $info->{'rra[1].rows'} - 1;
my $corrupt_time
    = $lastup
    - $lastup % $cf_step
    - $info->{'rra[1].cur_row'} * $cf_step;

print "rra[1] row 0 for time $corrupt_time contains the value $empty_time!\n";

###################################
