#!/usr/bin/perl

# Version 2.0
# Written by Tom Dietel <tom@dietel.net> 
# August 2007

# Version 2.1
# Edited by AK & AF

# Version 2.2
# Edited by AF

# Version 2.3
# Edited by AA

#use strict;
use POSIX;
use DBI;

$debug = 1;

# Set to 1 if reding HD ROBtest logfiles
$HDrobtest = 1;

my $iMCMCounter = 0;

if (!$HDrobtest){
	# if the first argument is omitted - then take a look in
	# _current/ directory for the last 'ce-laser-ID.log' File
	if (!$ARGV[0]) {   
	    $laserIDName="ce-laser";

	    my($tempFile)="DelMe.txt";
	    system("ls -t _current/ce-laser* > $tempFile");
	    open INtemp, "<$tempFile";
	  FILE:while (<INtemp>) {
	      my($line) = $_;
	      chomp($line);
	      if ($line =~ /([-a-z0-9]*.log)/){
		  $infile = "_current/$1";
	      }
	      last FILE if ($infile)
	      }    
	    system("rm $tempFile");    
	}
	else { $infile = shift;};
}
else{
	########### MODIFIED FOR HD ROBTEST ############################
                if (!$ARGV[0]) {
			print "Missing input logfile! \n";
		}
		else { $infile = shift;};
}

print "\n ********** \n";
print "\n The following log-file will be used: $infile\n";


open IN, "<$infile";
# Prepare the database connections and select/insert statements for
# gateDB and Venelin's/Stefans's MCM database


# The MCM DB is in the HD trd.net network, therefore an ssh tunnel is
# needed, and we connect to a port on localhost.
# The ssh tunnel can be started with:
#    ssh -L 3307:db01:3306 trd@trdro1.physi.uni-heidelberg.de



#WICHTIGE DB-VERBINUNG UNBEDINGT WIEDER ANSCHALTEN!! 
#ALTE VERSION:
#my $dbh_mcmdb = DBI->connect("DBI:mysql:dbname=mcmdb;host=127.0.0.1;port=3307", "mcm",
#'mcm123');

#
# This database and the tabel seams to be the wrong one 
# changed 16.11.2009
#
# my $dbh_mcmdb = DBI->connect("DBI:mysql:dbname=mcm;host=trdro1.physi.uni-heidelberg.de;port=33060", "mcm",
# 'mcm123');
# 
# # A statement to collect all MCM "IDs" that match a laser/TRAP number
# my $sth_list_mcms = $dbh_mcmdb->prepare("SELECT MCM ".
# 					"FROM mcmtbl ".
# 					"WHERE ChipId=? ".
# 					"GROUP BY MCM ".
# 					"ORDER BY MCM");


#
# changed to gateDB and to the table mcm_test
# 16.11.2009
# 
my $dbh_mcmdb = DBI->connect("DBI:Pg:dbname=gateDB;host=alice00.physi.uni-heidelberg.de", "alice",
'alice!@#');

# A statement to collect all MCM "IDs" that match a laser/TRAP number
my $sth_list_mcms = $dbh_mcmdb->prepare("SELECT mcm ".
          "FROM mcm_test ".
          "WHERE ChipId=? ".
          "GROUP BY MCM ".
          "ORDER BY MCM");

          
# Connection to the gateDB 

# The gateDB allows connections from a number of hosts, but can also be
# tunneled over ssh. The tunnel can be started with the ssh option -L.

# ssh tunnel 
#my $dbh_gatedb = DBI->connect("DBI:Pg:dbname=play;host=localhost",
#			      "alice", 'alice!@#',
#			      {'RaiseError' => 1});

my $dbh_gatedb = DBI->connect("DBI:Pg:dbname=gateDB;host=alice00.physi.uni-heidelberg.de",
			      "alice", 'alice!@#',
			      {'RaiseError' => 1});

# no tunnel
#my $dbh_gatedb = DBI->connect("DBI:Pg:dbname=gateDB;host=alice00.physi.uni-heidelberg.de",
#			      "alice", 'alice!@#',
#			      {'RaiseError' => 1});

# INSERT statement for new MCMs
my $sth_insert_mcm = 
    $dbh_gatedb->prepare("INSERT INTO mcm ".
			 "     (label_num,laser_num,rob_id,rob_pos,person)".
			 "VALUES (?,?,?,?,?)");

# UPDATE an existing MCM with a new laser number
my $sth_update_mcm = 
    $dbh_gatedb->prepare("UPDATE mcm ".
			 "SET laser_num = ?".
			 "WHERE mcm_id = ?");

#my $sth_move_mcm = 
#    $dbh_gatedb->prepare("UPDATE mcm ".
#			 "SET rob_id=?, rob_pos=?, loc_id=NULL".
#			 "WHERE mcm_id=?");

# Remove an MCM from its current position on a ROB
my $sth_remove_mcm = 
    $dbh_gatedb->prepare("UPDATE mcm ".
			 "SET rob_id=NULL, rob_pos=NULL, ".
			 "    loc_id=(SELECT loc_id FROM loc WHERE name='removed mcm') ".
			 "WHERE mcm_id=?");

# Query the gateDB for the MCM that is currently sitting in a certain place
my $sth_query_mcmpos = 
    $dbh_gatedb->prepare("SELECT mcm_id, label_num, laser_num ".
			 "FROM mcm ".
			 "WHERE rob_id=? AND rob_pos=?");

my $sth_query_robpos = 
    $dbh_gatedb->prepare("SELECT roc_type || '_' || roc_serial, roc_pos ".
			 "FROM rob ".
			 "WHERE rob_id=?");


#User initials
my $person = "NONE";

if ( !$HDrobtest){
	# Ask user for her initials
	print "Enter your initials for modifications in the gateDB: ";

	$person = <>;
	chop $person;
	print "Person: $person \n ";
	}

# =================================================================
#                            Main loop                             
# =================================================================
#                                                                  
# Loop over input files and enter all information about MCMs into  
# the gateDB.                                                      
#                                                                  
# =================================================================

$rob_posAK = "NONE";
$rob_id = "NONE";
$rob_posAK_old = "NONE";

if ($HDrobtest){
	while (<IN>) {
        	if ( /^Name:\s*([1234][AB])_(\d*)$/ ) {
        		$rob_type = $1;
        		$rob_id   = $2;
        	}
	
		#Get initials from logfile
        	if ( /^Tester:\s*(.*)$/ ) {
        		$person = $1;
        	}
	
	}
        print "\n Board: $rob_id Tester: $person \n";
	print "\n ********** \n";
}

close IN;

open IN, "<$infile";

while (<IN>) {

if (!$HDrobtest){    
    # ------------------------------
    # Read MCM information from file
    # ------------------------------

    # Alter/extend this section to support other file formats

	#########################################################################
	# OLD VERSION
	#    
	#    my $rob_id = "NONE";
	#    my $rob_posAK = "NONE";
	#    if (/ROB\# ([0-7]*)/)
	#    {
	#	$rob_posAK = $1;
	#	print "\nChecking ROB on Pos ";
	#	print $rob_posAK;
	#	print " . . .\n"
	#    }
	#    
	#    if (/gatedb:info_mcm_laser_id=([0-9]*)-([0-9]*)-0x([0-9A-Fa-f]*)/) {   
	#     #  /gateDB:laserid=(\d*):(\d*):0x([0-9a-fA-F]*)/) 
	#	$rob_id  = $1;
	#	$rob_pos = $2;
	#	$laserid = hex($3);
	#    }
	#
	#
	#
	#    # Go to next line if no information was found
	#    if ($rob_id eq "NONE") { 
	#	next;
	#    }
	#
	# OLD VERSION
	########################################################################


	########################################################################
	#NEW VERSION TO FIT NEW OUTPUT
	# DATA SAMPLE:	Rob 0, ALI-ID 0: Laser-Id 0x1bd68, dec 114024
	#		Rob 5, ROB-ID 0x243fc946, ALI-ID 17: Laser-Id 0x2261a, dec 140826
	#		ROB_posAK: Rob 0,1,2...7
	#		rob_pos ALI-ID 0,1,2...17
	#		laserid dec xxxxxx 
	#		    
	    $rob_pos = "NONE";
	    #print "I wars here\n";

	    #if (/Rob.([0-9]*).*ALI-ID.([0-9]*):*Laser-Id.([0-9A-Fa-f]*).*dec.([0-9]*)\n/) 
	    #if (/Rob.*\n/) 
    
	#    if (/Rob.([0-9]*)..ROB-ID.0x([0-9a-fA-F]*)..ALI-ID.([0-9]*)..Laser-Id..........dec.([0-9]*).*\n/) 
	    if (/Rob.([0-9]*)..ROB-ID.0x([0-9a-fA-F]*)..ALI-ID.([0-9]*)..Laser-Id.0x([0-9a-fA-F]*)..dec.([0-9]*).*\n/) 
	    {
		$rob_posAK  = $1;
		$rob_id = hex($2);
		$rob_pos = $3;
		$laserid = $5;
		print "I found some infos:  ROB_POS: $rob_posAK  ROB_ID: $rob_id  MCM number: $rob_pos   LaserID: $laserid \n";
		$iMCMCounter = $iMCMCounter+1;
		#print "I found somthing\n";
    	}
	
	#    if ($rob_posAK ne $rob_posAK_old)
	#    	{
	#	print "\nNEW ROB REACHED IN LOGFILE\n";
	#	print "Please enter the ID of the ROB on Pos. $rob_posAK : ";
	#	$rob_id=<STDIN>;
	#	chop $rob_id;
	#	$rob_posAK_old = $rob_posAK;
	#	}


	    # Go to next line if no information was found
	    if ($rob_pos eq "NONE") { 
	    	print "Found nonrelevant line in $infile ... skip it.\n";
		next;
	    }
	
	# END OF CHANGES
	#################################################
}
else{
	########### READ HD-ROBTEST LOGFILES ############
	$rob_pos = "NONE";
        if ( /^Slave\s([0-9]*)\s.MCM\s([0-9]*).\shas\sCHIPID.0x([0-9a-fA-F]*)\s.\s([0-9]*)(.*)$/) {
		$slave = $1;
		$rob_pos = $2;
                if ( $rob_pos eq "NONE") {
			next;
		}
		$laseridhex = $3;
		$laserid = $4;
		#print "\n I found some infos:  ROB_ID: $rob_id  MCM number: $rob_pos   LaserID: $laserid \n";
		$iMCMCounter = $iMCMCounter+1;
                #printf "Slave: $slave Rob_pos: $rob_pos Laser-id: $laserid \n"; 
	}
	else {
	next;
	}
}


    
    # ----------------------------------------------
    # Query databases for information about this MCM
    # ----------------------------------------------

    $sth_query_mcmpos->execute($rob_id, $rob_pos);
    my $roc_id="not set";
    my @oldmcm;
    if (@oldmcm = $sth_query_mcmpos->fetchrow_array) {
	
	if ( $oldmcm[2] == $laserid ) {
	    # The right MCM seems to be in the gateDB, skip everything else
	    next;
	}
    }

    $sth_query_robpos->execute($rob_id);
    
    if (@row = $sth_query_robpos->fetchrow_array) {
## $rob_desc is set in a wrong way.... ???
##	$rob_desc = "ROB $rob_id (on ".$row[0]." pos $rob_pos)";
	$rob_desc = "ROB $rob_id (on ".$row[0]." pos $rob_posAK)";
	$roc_id=$row[0];
    } else {
	$rob_desc = "ROB $rob_id";
    }

    # Get list of possible MCMs from MCM DB
    $sth_list_mcms->execute(sprintf "0x%X", $laserid);

    my @mcm_nums = (); 
    while(@row = $sth_list_mcms->fetchrow_array) {
	push @mcm_nums, ($row[0]);
    }
    

    # ------------------------------------
    # Ask the user for the real MCM number
    # ------------------------------------

    if ($#mcm_nums < 0) {

	#print "\n\nMCM on pos $rob_pos of $rob_desc: laser# $laserid\n\n";
	#print "MCM with ChipId $laserid not found in MCM DB!\n";
	#print "\n";
	#print "This is most likely due to an outdated MCM DB. Please contact\n";
	#print "Stefan Zimmer to have the DB updated.\n";
	#print "\n";
	#print "In the meantime, please enter the MCM number by hand: ";
	
	
	if (!$HDrobtest){    
		print "\n\n Found MCM without information in gateDB or MCM-DB!!!\n";
		print "\n   ROC $roc_id\n";
		print "   ROB on pos $rob_posAK with the ROB_ID $rob_id\n";
		print "   MCM on pos $rob_pos with the laser_id $laserid\n";
		print "\nEnter the MCM_ID by hand: ";
	} else {
		print "\n\n Found MCM without information in gateDB or MCM-DB!!!\n";
                if ($rob_pos eq 16){ print "\n *** Board Merger (BM) *** \n";}
                elsif ($rob_pos eq 17) {print "\n *** Half Chamber Merger (HM) *** \n";}
		else {print "\n ***  MCM on pos $rob_pos *** \n";}
		print "\n";
		print "\n Please enter the MCM LABEL by hand: ";
	}

	$real_mcm_num = <>;
	chop $real_mcm_num;

    } elsif ($#mcm_nums == 0) {

	# There is only one choice, take it.
	$real_mcm_num = $mcm_nums[0];

    } elsif ($#mcm_nums < 100) {

	if (!$HDrobtest){    
		#print "\n\nMCM on pos $rob_pos of $rob_desc: laser# $laserid\n\n";
		#print "\n\nMCM on pos $rob_pos: laser# $laserid\n\n";
		#print "Several MCMs match this laser number.\n";
		#print "\n";
		#print "Please choose one from the list, or enter the number by \n";
		#print "hand (e.g. if the test record is not yet in the MCM DB).\n";
		#print "\n";
		print "\n\nFound MCM with not unique mcm-ID.\n";
		print "\n   ROC $roc_id\n";
		print "   ROB on pos $rob_posAK with the ROB_ID $rob_id\n";
		print "   MCM on pos $rob_pos with the laser_id $laserid\n";
		print "\nPlease choose from list:\n";
		}
	else {
		print "\n\nFound MCM with not unique mcm-ID.\n";
                if ($rob_pos eq 16) {print "\n *** Board Merger (BM) *** \n";}
                elsif ($rob_pos eq 17) {print "\n *** Half Chamber Merger (HM) *** \n";}
		else {print "\n ***  MCM on pos $rob_pos *** \n";}
		print "\n";
		print "\n Please choose the MCM LABEL from list:\n";
	}


	for ($i=0; $i<=$#mcm_nums; $i++) {
	    print "     ".$i.": ".$mcm_nums[$i]."\n";
	}

	print "\n";
	print "Enter the MCM number or list position: ";
	$real_mcm_num = <>;
	chop $real_mcm_num;
	
	if ($real_mcm_num < 100) {
	    $real_mcm_num = $mcm_nums[$real_mcm_num]; 
	}

    } else {

	if (!$HDrobtest){    
		print "\n\nMCM on pos $rob_pos of $rob_desc: laser# $laserid\n\n";
		print "Several MCMs match this laser number.\n";
		print "\n";
		print "There are too many MCMs matching this laser number.\n";
		print "\n";
		print "Please enter the MCM number: ";
	} else {
                if ($rob_pos eq 16) {print "\n *** Board Merger (BM) *** \n";}
                elsif ($rob_pos eq 17) {print "\n *** Half Chamber Merger (HM) *** \n";}
		else {print "\n ***  MCM on pos $rob_pos *** \n";}
		print "\n There are too many MCMs matching its laser number.\n";
		print "\n";
		print "Please enter the MCM LABEL number: ";
	}
	
	$real_mcm_num = <>;
	chop $real_mcm_num;

    }
	

    # -----------------
    # Update the gateDB
    # -----------------

    if ( @oldmcm ) {

	# according to gateDB, another MCM is sitting in this position, we nee 
	# to check this first
	
	if ($oldmcm[1] == $real_mcm_num) {

	    # it seems the laser number has changed for this MCM: update
	    if ($debug) {
		print "UPDATE $mcm_id\n";
	    }
	    $sth_update_mcm->execute($laserid, $oldmcm[0]);

	} else {

	    # there was a different MCM, probably the board has been repaired, 
	    # and the old MCM was replaced

	    # Remove the old MCM and insert the new one
	    if ($debug) {
		print "REMOVE ".$oldmcm[0]."\n";
	    }

	    $sth_remove_mcm->execute($oldmcm[0]);

	    if ($debug) {
		print "INSERT: mcm $real_mcm_num, laser $laserid, ROB $rob_id, ";
		print "POS $rob_pos, WHO $person\n";
	    }

	    $sth_insert_mcm->execute($real_mcm_num, $laserid, $rob_id, $rob_pos, $person);
	}
    } else {

	if ($debug) {
	    print "INSERT: mcm $real_mcm_num, laser $laserid, ROB $rob_id, ";
	    print "POS $rob_pos, WHO $person\n";
	}

	# There is no MCM in this position, we can insert the new one:
	$sth_insert_mcm->execute($real_mcm_num, $laserid, $rob_id, $rob_pos, $person);
    }
	
    
}

print "\nInformation of $iMCMCounter checked";

if (!$HDrobtest){    
	if ($iMCMCounter == 138)
		{
		print "\nNumber of MCM matches number of MCMs on C1-ROCs... OK";
		}
	
	elsif ($iMCMCounter == 104)
		{
		print "\nNumber of MCM matches number of MCMs on C0-ROCs... OK";
		}
	else
		{
		print "\n+------------------------------------+";
		print "\n| Number of MCM does NOT matches the |";
		print "\n| number of MCMs on C1 or C0 ROCs!!! |";
		print "\n|         PLEASE CHECK               |";
		print "\n+------------------------------------+";
		}
}
else{
	if ($iMCMCounter == 17)
		{
		print "\nNumber of MCM matches number of MCMs on ROB types 1,2,4 A/B ... OK";
		}
	
	elsif ($iMCMCounter == 18)
		{
		print "\nNumber of MCM matches number of MCMs on ROB types 3 a/B ... OK";
		}
	else
		{
		print "\n+------------------------------------+";
		print "\n| Number of MCM does NOT matches the |";
		print "\n| number of MCMs on C1 or C0 ROCs!!! |";
		print "\n|         PLEASE CHECK               |";
		print "\n+------------------------------------+";
		}



}
print "\n\nCheck-LaserIDs - Script is DONE !\n";
$sth_list_mcms->finish();

