#!/usr/bin/perl

#use strict;
use POSIX;
use DBI;

system('. target_type > out_target_type');

#print $basename;
my $basename = $ENV{'BASENAME'};
my $tester = $ENV{'PERSON'};

#print "BASENAME: $basename\n";


if( $basename =~ m/([1234][AB])_(\d*)/ ){
$temp = $1;
$number = $2;
}


my $date=`/bin/date '+%Y-%m-%d %H:%M:%S'`;

my $chinjerr = "not performed";
my $scsnerr = "ERROR";
my $traperr = "not performed";
my $pasaerr = "not performed";
my $nierr = "not performed";
my $orierr = "not performed";
my $stresserr = "not performed";
my $state = "bad";

$type=join "", "T", $temp;
print "$type\n";

#DB upload error
my $dbfile = shift or die "No db-upload log-file";
open IN, "<$dbfile";

while (<IN>) {


    if ( /^Db_upload:\s*(.*)$/ ) {
        $dberr = $1;

    }
}

close $dbfile;




print "Type: $type\n";
print "Number: $number\n";
print "Date: $date\n";
print "CHINJ: $chinjerr\n";
print "SCSN: $scsnerr\n";
print "TRAP: $traperr\n";
print "PASA: $pasaerr\n";
print "NI: $nierr\n";
print "ORI: $orierr\n";
print "STRESS: $stresserr\n";
print "DB-upload: $dberr\n";
print "Status: $state\n";
print "Operator: $tester\n";




$dbh = DBI->connect("DBI:Pg:dbname=robtestproduction;host=alice.physi.uni-heidelberg.de",
                       "robocop", 'trdrob01')
                       or die "Connection Error: $DBI::errstr\n";
print "$DBI::errstr";


$dbh->begin_work();

$sth = $dbh->prepare("SELECT * FROM boardtests WHERE serialnumber=? AND boardtype=?;");
$sth->execute($number, $type);


if ( ! $sth->fetchrow_array() ) {

	$sth = $dbh->prepare("INSERT INTO boardtests(serialnumber, boardtype, testdate,scsnquicktest, preinchargetest,
                         traptest, pasatest, netwintest,stresstest,orireadouttest, dbupdate , state , operator ) 
                         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,? )");

        $sth->execute($number, $type,$date, $scsnerr, $chinjerr,$traperr,$pasaerr,$nierr, $stresserr, $orierr, $dberr,$state, $tester);
        }
else{
        $sth = $dbh->prepare("UPDATE boardtests SET testdate=? , scsnquicktest=? ,  preinchargetest=? ,
                        traptest=? , pasatest=? , netwintest=? , stresstest=?,
                        orireadouttest=? , dbupdate=? ,  state=? ,  operator=? 
                        WHERE serialnumber=? AND  boardtype=?");
        $sth->execute($date, $scsnerr, $chinjerr,$traperr,$pasaerr,$nierr, $stresserr, $orierr, $dberr,$state, $tester,$number,$type);

}


$dbh->commit;



$sth->finish();
$dbh->disconnect;



	
