#!/usr/bin/perl

#use strict;
use POSIX;
use DBI;

system('. target_type > out_target_type');


my $basename = $ENV{'BASENAME'};

my $person = $ENV{'PERSON'};

my $result = "2";

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

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

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

my $form=0;
my $ver=2;
my $confirm_new_rob = 0;

$loc = "PI ROB-Test";


my $logfile = shift or die "No log file given.";
my $pdffile = shift or die "No pdf file given.";
my $tgzfile = shift or die "No tgz file given.";
my $picfile = shift or die "No pic file given.";

print "Name: $type-$id\n";
print "Date: $date\n";
print "Tester: $person\n";
print "Result: $result\n";
print "SCSN: $scsnerr\n";
print "TRAP: $traperr\n";
print "PASA: $pasaerr\n";
print "NI: $nierr\n";
print "ORI: $orierr\n";
print "Comment: $comment\n";

$pdf_loid = -1;
$tgz_loid = -1;
$pic_loid = -1;


undef ($scsnerr) if ($scsnerr =~ /^\s*$/);
undef ($traperr) if ($traperr =~ /^\s*$/);
undef ($pasaerr) if ($pasaerr =~ /^\s*$/);
undef ($nierr)   if ($nierr   =~ /^\s*$/);
undef ($orierr)  if ($orierr  =~ /^\s*$/);



my $dbh = DBI->connect("DBI:Pg:dbname=gateDB;host=alice.physi.uni-heidelberg.de",
		       "alice", 'alice!@#')
		       or die "Connection Error: $DBI::errstr\n";
print "$DBI::errstr";

$dbh->begin_work();

print "$id'n";

$sth = $dbh->prepare("SELECT * FROM rob WHERE rob_id=$id;");
$sth->execute();

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

    if ($confirm_new_rob) {
	print "ROB not found, do you want to insert it [Y/n]? ";
	$yn = <STDIN>;
	chop $yn;

	if ($yn ne 'y' and $yn ne 'Y' and $yn ne '') {
	    print "\n...then I'm out of here!\n";
	    exit;
	}
    }


    if (!defined $person) {
	print "Enter your initials: ";
	$person = <STDIN>;
	chop $person;
    }

    if (!defined $loc) {
	print "Your location [SMint]: ";
	$loc = <STDIN>; chop $loc;
	
	$loc = 'PI ROB-Test' if ($loc eq '');
    }
    $sth = $dbh->prepare("INSERT INTO rob(form,type,ver,rob_id,person,loc_id) ".
                        "VALUES (?,?,?,?,?,(SELECT loc_id FROM loc ".
                        "                   WHERE name=?));");


    $sth->execute($form,$type,$ver,$id,$person,$loc);

}


$pdf_loid = upload_file($dbh,$pdffile,"","application/pdf");
$tgz_loid = upload_file($dbh,$tgzfile,"","application/gzip");
$pic_loid = upload_file($dbh,$picfile,"","image/jpeg");

$sth = $dbh->prepare("INSERT INTO rob_test ".
		     "VALUES (?,?,?,?,?,?,?,?,?,".
		     "        (SELECT file_id FROM file WHERE loid=?),".
		     "        (SELECT file_id FROM file WHERE loid=?),".
		     "        (SELECT file_id FROM file WHERE loid=?));");

$sth->execute($id,$date,$result,
	      $scsnerr,$traperr,$pasaerr,$nierr,$orierr,
	      $comment, $pdf_loid, $tgz_loid, $pic_loid);


$sth = $dbh->prepare("UPDATE rob SET status=? WHERE rob_id=?");
$sth->execute($result,$id);


$dbh->commit;


$dbh->disconnect;




sub upload_file () {

    my $dbh      = $_[0];
    my $filename = $_[1];
    my $dbname   = $_[2];
    my $mimetype = $_[3];

    my $nbytes;

    open INFILE, "<$filename";
    binmode INFILE;

    my $buf;
    my $len = read INFILE,$buf,100000000;

    close INFILE;


    my $lobjId = $dbh->func($dbh->{pg_INV_WRITE}, 'lo_creat');
    my $lobj_fd = $dbh->func($lobjId, $dbh->{pg_INV_WRITE} , 'lo_open');
    my $nbytes = $dbh->func($lobj_fd, $buf, $len, 'lo_write');

    my $sth = $dbh->prepare("INSERT INTO file(name,mime_type,loid) ".
			 "VALUES (?,?,?);");
    $sth->execute($filename, $mimetype, $lobjId );
    

    return $lobjId;


};
