#!/usr/local/bin/perl

#########################################################################################
# This is the prestart script for the GLueX BCAL test 2006 DAQ system.
# It is run during the
# CODA "prestart" transition and is responsible for filling certain entries
# in the online database.
# 
# 9/16/06  David Lawrence
#########################################################################################


### Set database access parameters
$msql_host = "clonxt2";
$mysql_host = "xdaq";
$mysql_user = "gluex";
$mysql_pass = "qcd!confine";
$mysql_db = "gluex_online";

########################## Collect values to insert in database ####################
### Get Current run number (Geez, it's ridiculous what we havce to do to get the run number)
$sql = "SELECT runNumber FROM sessions WHERE name='bcaltest'\\g";
$result = `echo \"$sql\" | msql -h $msql_host bcaltest | grep \"|\" | grep -v runNumber`;
@tmp = split(/\s+/, $result);
$runNumber =  $tmp[2];

# Dummy check on run number
if($runNumber<1000){
	print "Run Number is less than 1000!. This just can't be right.\n";
	exit(0);
}

# Current run configuration is placed in the file
# /usr/local/halld/config/coda/coda_config.txt by the download.pl script.
# However, we retrieve it the same way as we get the run number just
# to be less dependant on outside scripts.
$sql = "SELECT config FROM sessions WHERE name='bcaltest'\\g";
$result = `echo \"$sql\" | msql -h $msql_host bcaltest | grep \"|\" | grep -v config`;
@tmp = split(/\s+/, $result);
$runtype =  $tmp[2];

# Make initial, empty entry into RunID table,`.
$query = "INSERT INTO RunID (Run_Number,Run_Type,Run_Status)";
$query .= " VALUES($runNumber,'$runtype','IN PROGRESS')";
#print"$query\n";
print `mysql -e \"$query\" -h $mysql_host -u $mysql_user -p$mysql_pass $mysql_db`;

# Update entry with trigger configuration
$file = "/usr/local/halld/config/$runtype".".trig";
$trigconf = `head -n55 $file`;
$trigconf =~ s/\n/\\n/g;
$query = "UPDATE RunID SET Trigger_Configuration='$trigconf '";
$query.= " WHERE Run_Number=$runNumber AND Run_Type='$runtype'";
#print"$query\n";
print `mysql -e \"$query\" -h $mysql_host -u $mysql_user -p$mysql_pass $mysql_db`;

### Launch GUI to get user info
print "-------- start GUI output --------\n";
print `unset TCL_LIBRARY; unset TK_LIBRARY; /usr/local/halld/online/scripts/prestart/prestart_gui.tcl $runNumber $runtype`;
print "--------- end GUI output ---------\n";

print "-------- start script output --------\n";
#system("/usr/local/primex/online/scripts/prestart/prestart_finish.pl &");
print "--------- end script output ---------\n";

