#!/usr/bin/perl

# this script take position info from the steering file xml file (hub, card,pair,ab), and update LCMode in FAT database in table domtune.
# The output is a sql file udateFAT.sql and should be executed using : mysql FAT -u root -p < updateFAT.sql
# a necessary input file is in.xml, which is any xml steering output.
 
open (SQL,">updateFAT.sql") || die print "cannot open output SQL file";
print SQL "use fat ;\n";
print SQL "update domtune set domhub=''; \n";
# write to a file the dom informtion from a xml file.
open (OLDSTDOUT,">&STDOUT") or die "cant dup STOUT: $!";
open (STDOUT, ">dompos.temp");
$out=system("grep","domId","./LC-ATWD0.xml") || print "cannot find input ???.xml";
close STDOUT;
open (STDOUT,">&OLDSTDOUT") || die "cant restore STDOUT: $!";
open (positionFile,"dompos.temp");
$enough=1;
print " *************************\n ** Welcome to updateDB **\n *************************\n You can now manually change the LCmode. 
for each DOM enter: \n 0,1,2,3 - to change to new mode. \n [Enter]/else - to leave LCmode unchanged \n 99 to stop this annoying procedure.\n";

while (<positionFile>) {
	@sr=split("\'",$_);
	$mbid=$sr[1];
	$name=$sr[3];
	$domhub=$sr[5];
	$card=$sr[7];
	$pair=$sr[9];
	$ab=$sr[11];
#	print "mbid= $mbid \n thename=$name \n domhub=$domhub \n card=$card  pair=$pair  ab=$ab \n ";
	$last=substr($name,-3,3);
	$lcmode=1;
	if ($last eq "DOM" ) { $lcmode=0;}
if ($enough==1) {
    
    print "$domhub.$card$pair$ab  DOM $name, $mbid LCmode was set to $lcmode. Change to: ";

	$in=<STDIN>;
	chomp $in;
	if ($in eq "99") {$enough=0;}
	if ($in ne "") {
	    if ($in eq "0") {$lcmode=0;}
	    if ($in eq  "1") {$lcmode=1;}
	    if ($in eq "2") {$lcmode =2;}
	if ($in eq "3") {$lcmode=3;}
	}
    print "     new LCmode is $lcmode \n";
}

	$dor="$domhub.$card$pair$ab";
if ($name ne "") {
print SQL "#\n# $name $mbid:  \n# ============================;\n";
print SQL "update domtune set ab=\"$ab\" where mbid=\"$mbid\" ;\n" || print "cannot write to sql file";
print SQL "update domtune set pair=\"$pair\" where mbid=\"$mbid\";\n" || print "cannot write to sql file";
print SQL "update domtune set thename=\"$name\" where mbid=\"$mbid\";\n" || print "cannot write to sql file";
print SQL "update domtune set domhub=\"$domhub\" where mbid=\"$mbid\";\n" || print "cannot write to sql file";
print SQL "update domtune set card=\"$card\" where mbid=\"$mbid\" ;\n" || print "cannot write to sql file";
print SQL  "update domtune set lcmode=\"$lcmode\" where mbid=\"$mbid\" ;\n" || print "cannot write to sql file";
print SQL  "update domtune set dor=\"$dor\" where mbid=\"$mbid\" ;\n" || print "cannot write to sql file";
}
}
close SQL;
print " \n Output in updateFAT.sql. You should now issue the command: \n mysql fat -u tester -h sastrugi -p < updateFAT.sql \n";

$a=system("rm","dompos.temp");
#$a=system("mysql","fat","-u","tester","-p","-h","sastrugi","<","updateFAT.sql");
