#!/usr/bin/perl

use Time::Local;
use POSIX;
use RRDs 1.000101;
use Statistics::Descriptive;

$rrd = @ARGV[0];
if ($rrd eq "") {
        exit(0);
}

my ($seconds, $minutes, $hour, $monthday, $month, $year, $weekday, $yearday, $isdist) = localtime(time);
my $year = $year+1900;

my $end = timelocal(0,0,0,1,$month,$year);
my $start =  $end - 2592000;

my ($start95,$step95,$names95,$data95) = RRDs::fetch($rrd,'MAX','--start',$start,'--end',$end,'--resolution',300);

my($perc) = 0;
my($x,$y, $sam);
my($stat) = Statistics::Descriptive::Full->new();
my($samples) = 0;
foreach (@$data95) {
        $x = $_->[0];
        $y = $_->[1];
        # Substitute zero for missing samples
        if ($x eq "" || $y eq "") {
                        $sam = 0;
        } else {
                if ($x > $y) {
                        $sam = $x;
                } else {
                        $sam = $y;
                }
        }
        $samples++;
        $stat->add_data($sam);
}
if ($samples > 0) { $perc = ($stat->percentile(95))*8; }

print $perc;
