#!/usr/bin/perl -w
#
# Author: Petter Reinholdtsen <pere@td.org.uit.no>
# Date:   2000-03-02
#
# Based on a program by Mari Wang <mariw@tartarus.uwa.edu.au>.
#
# Read test data and store in SQL database for later processing.

my $dbtable  = "robios_timing";
my $dbname   = $ENV{DB_NAME}     || "pere_other";
my $dbhost   = $ENV{DB_HOST}     || "eeserver.ee.uwa.edu.au";
my $dbuser   = $ENV{DB_USER}     || "pere";
my $dbpasswd = $ENV{DB_PASSWORD} || "secret";

use DBI;

$dsn = "DBI:mysql:database=$dbname;host=$dbhost";
$dbh = DBI->connect($dsn, $dbuser, $dbpasswd);

die "Unable to connect to SQL database \"$dsn\n" unless ($dbh);

check_or_make_table($dbh);

#process text files
foreach $file (@ARGV) {
    open(FILE,"<$file") || die "Error opening $file";
    while (<FILE>) {
	$cpu_speed     = $1 if (/^Speed: (.*) Mhz/); # 35.7 Mhz
	$os_version    = $1 if (/^Version: (.*)$/);
	$robot_name    = $1 if (/^Name: (.*)$/);
	$function_type = $1 if (/^Testing: (.*)$/);
	last if (/^\s*$/);
    }
    if ($os_version =~ m/with/) { # 2.3l with Color Quickcam
	($os_version, $hw_info) = split(/with/, $os_version);
    }

    %data = ();

    while (<FILE>) {
	chomp;
	next if /^[\s\4]*$/;
	if (/^Warning:/) {
	    $Warning = $_;
	    write_warning_to_file();
	    next;
	}
	print "L: \"$_\"\n";
	($func)             = m/^(.*\))/;
	($ips)              = / (\d*\.\d*)$/;
	($func_name, $func_param) =
	    $func =~ m/^([^\(]+)(\(.*)/;
	$sql = "INSERT INTO $dbtable ".
	       "(cpu_speed, os_version, hw_info, robot_name, func_class, " .
	       "func_name, func_param, func_ips) VALUES (" .
	       "$cpu_speed, '$os_version', '$hw_info', '$robot_name'," .
	       "'$function_type', '$func_name', '$func_param', $ips" .
	       ");";

	$dbh->do($sql) || warn "SQL: $sql\n";

    }
}

sub check_or_make_table {
    my ($dbh) = @_;

    # Dummy search to check if the table exists
    $sth = $dbh->prepare("SELECT * FROM $dbtable where cpu_speed < 0;");
    if ( !$sth->execute) {
	$dbh->do("CREATE TABLE $dbtable (" .
		 "cpu_speed      float," .
		 "robot_name     text," .
		 "os_version     text," .
		 "hw_info        text," .
		 "func_class     text," .
		 "func_name      text," .
		 "func_param     text," .
		 "func_ips       float" .
		 ");");
    }
    $sth->finish;
}
