#!/usr/local/bin/perl
$mysql_host = "xdaq.jlab.org";
$mysql_user = "gluex";
$mysql_pass = "qcd!confine";
$mysql_db   = "gluex_online";

# Stop epics2et
`killall -9 epics2et`;

# Get filename of last file put in database by split_file.tcl
$sql = "SELECT File_Name FROM Run_Files ORDER BY ID DESC LIMIT 1";
$fname = `echo \"$sql\" | mysql -h $mysql_host -u $mysql_user -p$mysql_pass $mysql_db | grep -v File_Name`;
chomp $fname;

# Get number of events in the file.
$Nevents = `/usr/local/halld/bin/count_events /home/halldrun/raid/$fname`;
chomp $Nevents;

# Update number of events in last file in the database entry
$sql = "UPDATE Run_Files SET Number_of_Events=$Nevents WHERE File_Name='$fname'";
print `echo \"$sql\" | mysql -h $mysql_host -u $mysql_user -p$mysql_pass $mysql_db`;

# Get the total number of events for this run from the database
$sql = "SELECT Run_Number FROM Run_Files WHERE File_Name='$fname' LIMIT 1";
$runnumber = `echo \"$sql\" | mysql -h $mysql_host -u $mysql_user -p$mysql_pass $mysql_db | grep -v Run_Number`;
chomp $runnumber;
$sql = "SELECT SUM(Number_of_Events) AS Ntotal FROM Run_Files WHERE Run_Number=$runnumber GROUP BY Run_Number";
$Ntotal = `echo \"$sql\" | mysql -h $mysql_host -u $mysql_user -p$mysql_pass $mysql_db | grep -v Ntotal`;
chomp $Ntotal;

# Update RunID table with total events and end run time.
$sql = "UPDATE RunID SET Total_Number_of_Events=$Ntotal,End_Run_Time=Now() WHERE Run_Number=$runnumber";
print `echo \"$sql\" | mysql -h $mysql_host -u $mysql_user -p$mysql_pass $mysql_db`;

