#!/usr/bin/perl -w

# update-rrd.pl
# by mindc

use strict;
use RRDs;
use XML::Simple;
use POSIX qw(mktime);
use Data::Dumper;
use Getopt::Long qw(:config bundling pass_through);
use Carp;

$|++;

# defaults
my $stats_file = './stats.xml',
my $output_dir = '.';
my $debug = 0;

my $stats = {};

GetOptions(
    "i|input=s" => \$stats_file,
    "o|output=s" => \$output_dir,
    "d|debug" => \$debug,
    "h|help|usage" => \&usage,
);

usage() if $ARGV[0];

if ( open ( my $fh,'<',$stats_file )) {
    $stats = XMLin(
        $fh,
        KeyAttr => '',
        GroupTags => { projects => 'project' },
        ForceArray => [ 'project' ],
    );
    close $fh;
} else {
    croak "$stats_file $!";
}

unless ( -d $output_dir ) {
    croak "$output_dir $!";
}

print Dumper $stats if $debug;

foreach ( @{$stats->{projects}} ) {
    my $rrd_filename = $_->{project_url};
    for ( $rrd_filename ) {
        s!https?://!!;
        s!/$!!;
        s!/!_!g;
    }

    unless ( -r "$output_dir/$rrd_filename.rrd" ) {
        RRDs::create "$output_dir/$rrd_filename.rrd","--start=now-1d",
            "--step=3600",
            "DS:total:GAUGE:86400:0:U",
            "DS:expavg:GAUGE:86400:0:U",
            "DS:avgrac:COUNTER:86400:0:U",
            "RRA:LAST:0.5:1:20000",
            ;
    }

    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
    my $update = mktime(0,0,$hour,$mday,$mon,$year,0,0,$isdst);
    print "$output_dir/$rrd_filename.rrd ",
        "$update:$_->{user_total_credit}:",
        "$_->{user_expavg_credit}:",
        "@{[ int($_->{user_total_credit}) ]}\n" if $debug;

    RRDs::update "$output_dir/$rrd_filename.rrd", sprintf( "%s:%lf:%lf:%ld", $update, $_->{user_total_credit}, $_->{user_expavg_credit}, $_->{user_total_credit} );
    if ( my $err = RRDs::error ) {print "update: $err\n"}
}
exit;

sub usage {
    print "$0 [-i|--input=FILE] [-o|--output=DIR] [-d|--debug] [-h|--help|--usage]\n\n";
    exit(1);
}
