#!/usr/bin/perl

use DBI;

$dirname = shift;
$dirname= "_current" if $dirname =~ /^$/;
print "$dirname\n";

$filename = `ls -t $dirname/ce-laser* 2>/dev/null | head -1`;
exit unless $filename;

$person = `grep INITIAL $dirname/_setup | sed s/INITIAL=//`;
exit unless $person;

chop $person;



#$filename = shift or die "usage: check_laser_id.pl <logfile>";

open IN, "<$filename" or die "Unable to open file $filename";



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


$sth = $dbh->prepare("SELECT COUNT(1) AS cnt FROM mcm WHERE laserid=?");




$sth_resetrob = $dbh->prepare("UPDATE mcm ".
			      "SET loc_id=(SELECT loc_id FROM loc WHERE name='unknown'), ".
			      "           rob_id=NULL,rob_pos=NULL ".
			      "WHERE rob_id=?");


while (<IN>) {

    @alphabet = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 
		 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');


    if (/gatedb:info_mcm_laser_id=([0-9]*)-([0-9]*)-0x([0-9A-Fa-f]*)/ ) {

	$rob = $1;
	$pos = $2;
	$lid = hex $3;
	
	
	$sth_robpos = $dbh->prepare("SELECT loc ".
				    "FROM rob_inventory ".
				    "WHERE id=?");
	$sth_robpos->execute($rob);
	
	if ($row = $sth_robpos->fetchrow_hashref ) {
	    $robloc = $row->{'loc'};
	} else {
	    die "Unknown ROB!?! Where did you find this one???";
	}
	$sth_robpos->finish;


	$sth_findmcm = $dbh->prepare("SELECT mcm_id,laserid FROM mcm ".
				     "WHERE rob_id=? AND rob_pos=?");
	$sth_findmcm->execute($rob,$pos);
	
	$dblid = -999;
	$dbmcm = "";

	if ($row = $sth_findmcm->fetchrow_hashref ) {

	    $dbmcm = $row->{'mcm_id'};
	    $dblid = $row->{'laserid'};

	    if ($row->{'laserid'} != $lid) {
		print "Mismatch on ROB $rob position $pos: laserid is $lid, ";
		print "gateDB says ".$row->{'laserid'}."\n";


		print ("Do you want to delete the MCM information about ROB $rob ".
		       "in the gateDB? (y/n)");
		
		$answer = <>;

		if ($answer =~ /^y/) {
		    $sth_resetrob->execute($rob);
		    $sth_resetrob->finish;
		    die "Please re-run check_laser_id.pl\n";
		} else {
		    die "Mismatch\n";
		}
	    }
	}
	
	$sth_findmcm->finish;
	


	my $sth_alternatives = 
	    $dbh->prepare("SELECT mcm_id FROM mcm WHERE laserid=? ORDER BY mcm_id");
	    
	$sth_alternatives->execute($lid);

	my $i=0;
	%alternatives = ();
	

	while ( $row = $sth_alternatives->fetchrow_hashref ) {
	    $alternatives{$alphabet[$i]} = $row->{'mcm_id'};

	    $i++;
	}

	$sth_alternatives->finish;

	$count = scalar keys (%alternatives);
	
	if ($count != 1) {
	    print "\n\n\nCannot identify MCM $pos with laser ID $lid ";
	    print "on ROB $rob (located at $robloc).\n";
	    print "Please check the ID printed on the MCM.\n\n";

	    foreach $i (sort (keys %alternatives)) {
		print "     ".$i.": ".$alternatives{$i}."\n";
	    }

	    print "\n";

	    do {
		print "Enter a letter if the MCM is listed above, ";
		print "or the full ID [$dbmcm]: ";
		$real_mcm_id = <>;
		chop $real_mcm_id;
		
		if ($real_mcm_id =~ /^([a-z])$/) {
		    $real_mcm_id = $alternatives{$1};
		} elsif ($real_mcm_id =~ /^(\d+)$/) {
		    $real_mcm_id = $1;
		} elsif ($real_mcm_id =~ /^$/) {
		    $real_mcm_id = $dbmcm;
		    
		} else {
		    $real_mcm_id = -999;
		}
	    } until ($real_mcm_id > 0);
	    

	} else { 
	    # Assume that the laserid in the DB is correct
	    $real_mcm_id = (values %alternatives)[0];
	}	

    
	$sth_getinfo_mcm = $dbh->prepare("SELECT rob_id,rob_pos,laserid ".
					 "FROM mcm ".
					 "WHERE mcm_id=?");
	$sth_getinfo_mcm->execute($real_mcm_id);
    
	if ($row = $sth_getinfo_mcm->fetchrow_hashref ) {
	    
	    if (defined $row->{'rob_id'} and 
		( $row->{'rob_id'} != $rob or $row->{'rob_pos'} != $pos ) ) {
		
		print "The MCM ($real_mcm_id) is already sitting at another ";
		print "position (".row->{'rob_id'}."/".$row->{'rob_pos'}.").\n";
		print "I suggest to enter this MCM with a different ID.\n";
		print "Do you want to do that? (y/N) ";

		$confirm = <>;

		if ($confirm =~ /^y/ or $confirm == "automatic") {

		    $sth_getnextid = $dbh->prepare("SELECT max(mcm_id)+1 AS new_id ".
						   "FROM mcm ".
						   "WHERE mcm_id>99990000 ".
						   "  and mcm_id<99999999");
		    $sth_getnextid->execute();

		    if ($row = $sth_getnextid->fetchrow_hashref ) {
			$real_mcm_id = $row->{'new_id'};
		    }
		    $sth_getnextid->finish;
		    
		    $sth_setid_mcm = 
			$dbh->prepare("INSERT INTO ".
				      " mcm(mcm_id,laserid,person,loc_id) ".
				      "VALUES (?,?,?,(SELECT loc_id ".
				      "               FROM loc ".
				      "               WHERE name='unknown'))");
		    $sth_setid_mcm->execute($real_mcm_id, $lid, $person);
		    $sth_setid_mcm->finish;



		    print "\n\n   Please tell Tom (tom\@dietel.net) about this!\n\n";
		    print "Hit return!\n";
		    <>;
		    
		} else {
		    die "Please restart... Sorry for the inconvenience;-)";
		}

	    } elsif ($row->{'laserid'} != $lid) {
		    
		if ($row->{'laserid'} != -1) {
		    print "Laser ID in gateDB (".$row->{'laserid'};
		    print ") does not match read ID ($lid).";
		    
		    print "Are you sure the the MCM ID is correct (y/N)? ";
		    
		    $confirm = <>;
		} else {
		    $confirm = "automatic";
		}
		
		if ($confirm =~ /^y/) {
		    print "\n\n   Please tell Tom (tom\@dietel.net) about this!\n\n";
		    print "Hit return!\n";
		    <>;
		}
		    
		if ($confirm =~ /^y/ or $confirm == "automatic") {
		    $sth_setid_mcm = $dbh->prepare("UPDATE mcm ".
						   "SET laserid=?,person=? ".
						   "WHERE mcm_id=?");
		    $sth_setid_mcm->execute($lid, $person, $real_mcm_id);
		    $sth_setid_mcm->finish;
		    
		} else {
		    die "Please restart... Sorry for the inconvenience;-)";
		}
	    }
	} else {
	    
	    print "Unknown MCM. Is the ID really $real_mcm_id (y/N) ? ";
	    $confirm = <>;


	    if ($confirm =~ /y/) {
		$sth_new_mcm = 
		    $dbh->prepare("INSERT ".
				  "INTO mcm(mcm_id,laserid,person,loc_id) ".
				  "VALUES (?,?,?(SELECT loc_id ".
				  "              FROM loc ".
				  "              WHERE name='unknown'))");
		$sth_new_mcm->execute($lid, $person, $real_mcm_id);
		$sth_new_mcm->finish;

		print "Inserted a new MCM into the gateDB.";
		print "\n\n   Please tell Tom (tom\@dietel.net) about this!\n\n";
		print "Hit return!\n";
		<>;

	    } else {
		die "Please restart... Sorry for the inconvenience;-)";
	    }

	}
	$sth_getinfo_mcm->finish;


	

	$sth_newloc = $dbh->prepare("UPDATE mcm ".
				    "SET rob_id=?,rob_pos=?,loc_id=NULL,person=? ".
				    "WHERE mcm_id=?");
	
	$sth_newloc->execute($rob,$pos,$person,$real_mcm_id);
	$sth_newloc->finish;

	#print "Updated gateDB.\n\n";

    }
    
}

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