#!/usr/bin/perl
# doEvb.pl
# author Hiroyuki Sako
# 28.06.00

# input files are asumed to be the pipe

$|=1;

$catchPvicError = 1; #catch pvic error

$isPipe = 1; # use pipe as input file = 0

$evbDir = "/cdrShare01/cerescdr/cdr2k/evb";

chdir($evbDir);

chop($hostName = `hostname`);

if ($hostName =~ /(na45pc\d{2})/ ) {
    $host = $1;
} else {
    die "$0> cannot get host\n";
}


$run = "";
$burst = "";
$run = shift if defined @ARGV;
$burst = shift if defined @ARGV;

if (($run eq "")||($burst eq "")) {
    die "Usage: $0 run burst\n";
}

$statFile = "$evbDir/sta/$host";
$histFile = "$evbDir/hist/evb.hist";

#
$start = `date +"%D %T"`;
chop($start);
$status = "evb started";

$line = sprintf("$host %04d %04d %4d %6.2f %s %s %3d %3d %3d %s",
		$run, $burst, 0, 0, $start, "NA", 
		0, 0, 0, $status);

if (open (STAT, ">$statFile")) {
    print STAT "$line\n";
    close (STAT);
}

# 29.09.00 16:07 commented out   
#if (open (HIST, ">>$histFile")) {
#    print HIST "$line\n";
#    close (HIST);
#}

$errPvicOut = 0;
if ($catchPvicError == 1) {
    $outErrDir = "/pool/home/cerescdr/errData";
    chop($freePool = `df $outErrDir | tail -1`);
    ($dev, $total, $used, $avail, $usef, $disk) = split(' ', $freePool);
    print "free space in $outErrDir = $avail\n";
    if ($avail > 50*1024) { # 50 MB
	$errPvicOut = 1;
    }
}


$inDir = "/home/cerescdr/ebinp";

@inFiles = <$inDir/run????_burst????_branch??.dat>;

$index = 0;
@dataFile = ();

print "run $run, burst $burst\n";

foreach $inFile (@inFiles) {
    
    if ($inFile =~ /run(\d{4})\_burst(\d{4})\_branch(\d{2})\.dat/) {
	
	$dataFile[$index] = $inFile;
	
	$runTemp = int($1);
	$burstTemp = int($2);
	$branch = int($3);


	if (($runTemp != $run) || ($burstTemp != $burst)) {
	    # do not use this file
	    next;
	}

	if ($index == 0) {

	    $configFile = sprintf("$evbDir/config/run%04d-burst%04d.config",
				  $run, $burst);
	    
	    $outPath = getPath();
	    
	    if ($outPath eq "") {
		die "$0> cannot get path... check disk space. \n";
	    }
	    
	    $outFile = sprintf("$outPath/run%04d-burst%04d.dat",
			   $run, $burst);
	    
	    $sumFile = sprintf("$evbDir/sum/run%04d-burst%04d.sum",
			       $run, $burst);
	    
	    $logFile = sprintf("$evbDir/log/run%04d-burst%04d.log",
			       $run, $burst);
	    $evInfoFile = sprintf("$evbDir/evinfo/run%04d-burst%04d.evi",
				  $run, $burst);

	    if ($errPvicOut == 1) {
		$errPvicFile
		    = sprintf("$outErrDir/run%04d-burst%04d-branch09.dat",
			      $run, $burst);
	    }
	    
	    if (-e $configFile) {
		$cmd = "rm $configFile";
		system($cmd);
	    }

	    if (-e $outFile) {
		$cmd = "rm $outFile";
		system($cmd);
	    }
	    
	    if (-e $sumFile) {
		$cmd = "rm $sumFile";
		system($cmd);
	    }
	    
	    if (-e $logFile) {
		$cmd = "rm $logFile";
		system($cmd);
	    }
	    
	    if (-e $evInfoFile) {
		$cmd = "rm $evInfoFile";
		system($cmd);
	    }
	    
	    open(CONFIGFILE, "> $configFile")
		|| die "$0> failed to open $configFile";
	}


	if (($branch < 0) || ($branch>9)) {
	    next;
	}

	$active = 1;

	if ($isPipe == 0) {
	    $dataSize = `ls -s $inFile`;
	    chop($dataSize);
	    ($size, $name) = split(' ', $dataSize);
	    if ($size == 0) {
		$active = 0;
	    }
	}

	$line = sprintf("$branch $active $inFile\n");
	printf $line;
	printf CONFIGFILE $line;
	
	$index++;    
    }
}

close(CONFIGFILE);

if ($index == 0) {
    print "no input datafile found\n";
    print "Aborting...\n";
	

    $end = `date +"%T"`;
    chop($end);
    $status = "no input file. evb failed";
    $line = sprintf("$host %04d %04d %4d %6.2f %s %s %3d %3d %3d %s",
		    $run, $burst, 0, 0, $start, $end,
		    0, 0, 0, $status);

    system("sync");
    sleep(10);
    
    if (open (STAT, ">$statFile")) {
	print STAT "$line\n";
	close (STAT);
    }
    
    if (open (HIST, ">>$histFile")) {
	print HIST "$line\n";
	close (HIST);
    }
    exit;
}


if ($errPvicOut == 0) {
    $command = "$evbDir/evb $configFile $outFile $sumFile $evInfoFile > $logFile 2>&1";
} else {
    $command = "$evbDir/evb $configFile $outFile $sumFile $evInfoFile $errPvicFile > $logFile 2>&1";
}

system($command);
$end = `date +"%T"`;
chop($end);
print "end = $end\n";

# before cleaning up date file, check logFile
$status = `tail -1 $logFile`;
chop($status);
if ($status !~ /evb succeeded/) {
    $status = "evb failed";
}


$errFedc=0;
$errGrda=0;
$errPvic=0;
$error = `tail -1 $evInfoFile`;
chop($error);
if ($error =~ /error (\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+)/) {
    $errFedc = $1+$2+$3+$4+$5+$6+$7+$8;
    $errGrda = $9;
    $errPvic = $10;
}

$total = `tail -1 $sumFile`;
chop($total);


if ($total =~ /EOBL (\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+)/) {
    $nEventInBurst = $1;
    $nEvent   = $2;
    $iburst = $3;
    $nModules = $4;
    $size = $5*4./1024./1024.; # in MB max = 400MB = 100*1024 kb = 100000
    $date = $6;
    $time = $7;

    $line = sprintf("$host %04d %04d %4d %6.2f %s %s %3d %3d %3d %s",
		    $run, $burst,
		    $nEventInBurst, $size, $start, $end,
		    $errFedc, $errGrda, $errPvic, $status);
} else {
    $line = sprintf("$host %04d %04d %4d %6.2f %s %s %3d %3d %3d %s",
		    $run, $burst,
		    0, 0, $start, $end,
		    0, 0, 0, $status);
}

if ($isPipe == 0) {
    $command = "/bin/rm $inDir/run*_burst*_branch*.dat >& /dev/null";
    print "$command\n";
    system($command);
}

system("sync");
sleep(10);

open(STAT, ">$statFile") || die "$0> cannot open $statFile\n";
print STAT "$line\n";
close(STAT);

open(HIST, ">>$histFile");
print HIST "$line\n";
close(HIST);

# make link file
$line = `ls -s $outFile`;
($size, $path) = split(' ', $line);

if ($outFile =~ /(na45pc\d\d)/) {
    $CDR = $1;
} else {
    die "$0> cannot get CDR host = $CDR\n";
}

$TAPE_ROOT = "/cdrShare01/cerescdr/cdr2k/tape";
$linkFile = sprintf("$TAPE_ROOT/toTape/$CDR-run%04d-burst%04d.link",
		    $run,$burst);
open(TOTAPE, ">$linkFile");
print TOTAPE "$outFile $size\n";
close TOTAPE;

exit;


sub getPath {

# 600 MB. should be maximum possible data size
    $minFreeSpace = 600.*1024.;

    if (($host eq "na45pc08")
	||($host eq "na45pc10")) {
	
	@disks = (
		  "/shift/$host/data01",
		  "/shift/$host/data02",
		  "/shift/$host/data03",
		  "/shift/$host/data04",
		  "/shift/$host/data05"
		  );
    } # 03.10.00 use only upto 06
    elsif ($host eq "na45pc11") {
	@disks = (
		  "/shift/$host/data01",
		  "/shift/$host/data02",
		  "/shift/$host/data03",
		  "/shift/$host/data04",
		  "/shift/$host/data05",
		  "/shift/$host/data06"
		  );
    }
    elsif (($host eq "na45pc12")||($host eq "na45pc14")) {
	@disks = (
		  "/shift/$host/data01",
		  "/shift/$host/data02",
		  "/shift/$host/data03",
		  "/shift/$host/data04",
		  "/shift/$host/data05",
		  "/shift/$host/data06"
		  );
    } else {
	@disks = (
		  "/shift/$host/data01",
		  "/shift/$host/data02",
		  "/shift/$host/data03",
		  "/shift/$host/data04"
		  );
    }

    $path = "";
    foreach $disk (@disks) {
	@diskSizeList = `df -k $disk`;
	$free = 0;
	foreach $diskSize (@diskSizeList) {
	    if ($diskSize =~ /$disk/) {
		@space = ();
		@space = split(' ', $diskSize);
		$free = $space[3];
		last;
	    }
	}
	print "disk = $disk\n";
	print "free = $free\n";
	print "minFreeSpape = $minFreeSpace\n";
	
	if ($free > $minFreeSpace) {
	    $path = "$disk/cerescdr/daq2k/data";
	    print "path = $path\n";
	    last;
	}
    }
    return $path;
}

