#!/apps/perl/PRO/bin/perl

### perl modules built for PrimEx use on clon cluster
use Pezca;
Pezca::SetTimeout(1);
Pezca::SetRetryCount(0);

### Set database access parameters
$msql_host = "clon10";
$mysql_host = "clas-sc0";
$mysql_user = "primex";
$mysql_db = "primex_online";

### Make sure the EPICS_CA_ADDR_LIST environment variable is defined
if(length($ENV{"EPICS_CA_ADDR_LIST"})<1) {
	$ENV{"EPICS_CA_ADDR_LIST"} = "129.57.255.4 129.57.163.255 129.57.96.7 129.57.57.188";
}

########################## 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='primex'\\g";
$result = `echo \"$sql\" | msql -h $msql_host primex | 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);
}

############################ Update Existing rows #############################
### Update RunID database
$query = "UPDATE RunID SET End_Run_Time=NOW() WHERE Run_Number=$runNumber";
print "$query\n";
print `mysql -e \"$query\" -h $mysql_host -u $mysql_user $mysql_db`;

### Here, we update the number of events in the last file for the run
### in the Run_Files table and the total number of events in the
### RunID table. All but the last file will have the number of events
### updated by the split_file.tcl script just before the next file is
### opened. Hence, we only need to update the last file here.

### Get name of last file for this run. 
$query = "SELECT File_Name FROM Run_Files WHERE Run_Number=$runNumber";
$query .= " ORDER BY Time DESC LIMIT 1";
print "$query\n";
$result = `mysql -e \"$query\" -h $mysql_host -u $mysql_user $mysql_db`;
@tmp = split(/\s+/, $result);
$filename =  $tmp[1];

### Find number of events in last file and update DB
$nevents = `/usr/local/primex/builds/devel/bin/SunOS/count_events /mnt/raid?/stage_in/$filename`;
$query = "UPDATE Run_Files SET Number_of_Events=$nevents WHERE Run_Number=$runNumber AND File_Name='$filename'";
print "$query\n";
print `mysql -e \"$query\" -h $mysql_host -u $mysql_user $mysql_db`;

### Find total number of events in all files and update RunID table
$query = "SELECT SUM(Number_of_Events) FROM Run_Files WHERE Run_Number=$runNumber GROUP BY Run_Number";
print "$query\n";
$result = `mysql -e \"$query\" -h $mysql_host -u $mysql_user $mysql_db`;
@tmp = split(/\s+/, $result);
$Nevents_total =  $tmp[1];
$query = "UPDATE RunID SET Total_Number_of_Events=$Nevents_total WHERE Run_Number=$runNumber";
print "$query\n";
print `mysql -e \"$query\" -h $mysql_host -u $mysql_user $mysql_db`;


