#!/usr/bin/perl
use strict;
use warnings;
use DBI;

################ CONFIG HERE & in __DATA__ ################
my $conf_file = 'myconf.conf';                            #
my $pb        = "./parrotbench.gat -c $conf_file";        #
my $db        = 'benchmark.db';                           #
###########################################################

open (MYCONF, '>', $conf_file) or die "Unable to open $conf_file for writing : $!";

my @table;
push @table, /^([^:]+):/ and print MYCONF while <DATA>;

open (TESTS, '-|', "$pb -l" ) or die "Unable to call $pb : $!";
my @test = map { s/-/_/g; /^([^,]+),/ } <TESTS>;

my $dbh = DBI->connect( "dbi:SQLite2:dbname=$db","","");

Build_DB($dbh, \@table, \@test) if ! $dbh->selectrow_array( 'SELECT count(*) FROM sqlite_master' );

my $now = $ARGV[0] || time;
for my $table ( @table ) {
    my $sth = $dbh->prepare( "INSERT INTO $table (time) VALUES (?)" );
    $sth->execute( $now ) or die $dbh->errstr;
}

open (BENCH, '-|', "$pb -t") or die "Unable to call $pb : $!";

my @total;
while ( <BENCH> ) {
    next if $. < 3;    # Skip the first two lines
    chomp;
    my ($test, @time) = split " ";
    $_ =~ s/s$// for @time;
    $test =~ s/-/_/g;

    for ( 0 .. $#table ) {
        my $sth = $dbh->prepare( "Update $table[$_] SET $test = ? WHERE time = ?" );
        $total[$_] += $time[$_] eq '-' ? 0 : $time[$_];
        $sth->execute($time[$_], $now) or die $dbh->errstr;
    }
}
for ( 0 .. $#table ) {
    my $sth = $dbh->prepare( "Update $table[$_] SET total = ? WHERE time = ?" );
    $sth->execute($total[$_], $now) or die $dbh->errstr;
}

$dbh->disconnect;

sub Build_DB {
    my ($dbh, $table, $test) = @_;
    for my $table ( @{ $table } ) { 
        my $sth = $dbh->prepare(
            "CREATE TABLE $table (time, total, " . Gen_Columns( $test ) . ")"
        );
	$sth->execute() or die $dbh->errstr;
    }
}

sub Gen_Columns { return join ',' , @{ $_[0] } }
__DATA__
parrot:      /perl/parrot/parrot: .pasm .imc
perl_585_th: /usr/bin/perl:       .pl
python_234:  /usr/bin/python:     .py
ruby_181:    /usr/bin/ruby:       .rb
NOBENCH =    ^(arriter|overload|b\d|hash-utf)
