#!/usr/bin/perl -w

use strict;

use XML::Simple;

my $file = "/tmp/stats.xml";

unless (-e $file) {
    open XML, ">$file" or die;
    my $empty = {
        generators => {
            current => 0,
            results => {
                success => 0,
                cancelled => 0,
                timeout => 0,
                errors => 0,
                exceptions => 0
            }
        }
    };
    save($empty);
}

my $data = XMLin($file);

$data->{generators}{current}++;
$data->{generators}{results}{success} += 2;
$data->{generators}{results}{cancelled} += 2;
$data->{generators}{results}{timeout} += 2;
$data->{generators}{results}{errors} += 2;
$data->{generators}{results}{exceptions} += 2;

save($data);

print "Content-Type: application/xml\n\n";
print get_xml($data);

sub save {
    my ($xml) = @_;
    open XML, ">$file" or die "Can't write $file\n";
    print XML get_xml($xml);
    close XML;
}

sub get_xml {
    my ($xml) = @_;
    return XMLout($xml, RootName => 'stats', NoAttr => 1);
}
