#! /usr/bin/perl


# Usage: scanDBgrades.pl -m M7690-17-2 
# -----

# ----------------------------------------------------------------------
use Getopt::Std;
getopts('m:');

$dbDir   = "/home/l_tester/ptr/moduleDB";

#$testDir = "/home/l_tester/ptr/moduleTestsOld/psi46expert";
#$testDir = "/home/l_tester/ptr/moduleTests/psi46expert";
#$testDir = "/home/l_tester/ptr/merged/psi46expert";
#$testDir = "/home/l_tester/ptr/supervisor/tests";   
 
$tmp1 = $opt_m;
$tmp1 =~ s/\.\.//;
$tmp1 =~ s/\///g;
@ntmp = split(/\-/,$tmp1);
$name= $ntmp[0]."T-".$ntmp[2];

  
$tmp2 = $opt_m;
$tmp2 =~ s/\.\.//;

@mtmp = split(/\//,$tmp2);
$testNr=$mtmp[$#mtmp];  
@ntmp = split(/\-/,$mtmp[$#mtmp-1]);
$moduleNr=$ntmp[0];
 
$fnGrade = "";

if (-e "$dbDir/$opt_m/../finalGrade.txt" ) {system("rm -f $dbDir/$opt_m/../finalGrade.txt");}
open(GRADE, ">$dbDir/$opt_m/../finalGrade.txt") || die "==> Cannot open $dbDir/$opt_m/../finalGrade.txt\n";

$file = "$dbDir/grades.txt";
$rrr=`ls $file`;
if ( -e $file ) {
    getFnGrade($file);
}

if ( $fnGrade ne "A" && $fnGrade ne "B" && $fnGrade ne "C"  ) {

    if ((substr($opt_m,0,1) eq "R") ) {

	print "scanDBgrades> FINAL DB-GRADE not found. Will use overall grade ...\n";
	
	open(IN, "$dbDir/$opt_m/summaryTest.txt") || die "Cannot open $dbDir/$opt_m/summaryTest.txt\n"; 
	
	while (<IN>) {
	    if (/OVERALL/) {
		s/OVERALL GRADE //g;
		$fnGrade = $_;
	    }
	}

	print "scanDBgrades> FINAL GRADE (not DB)   ... $fnGrade\n";
    }
    else {
	$fnGrade = "tbd";
	print "scanDBgrades> FINAL GRADE    ... $fnGrade\n";
    }
}
else {

    print "scanDBgrades> FINAL DB-GRADE    ... $fnGrade\n";
}

print GRADE "FINAL DB-GRADE $fnGrade\n";
close(GRADE);
#----------------------------------------------------------------------------------------

sub getFnGrade() {
    my ($f) = @_;

    open(GR, "$f") || die "Cannot open $f\n"; 

    print "scanDBgrades> LOOKING FOR $moduleNr\'s grade\n";
    while (<GR>) {
	if (/$moduleNr/) {

	    s/$moduleNr //g;
	    $fnGrade = $_;

	    if ( $fnGrade ne "" ) {
		print "scanDBgrades> FOUND FINAL GRADE for $mod IN DB:  $fnGrade\n";
	    }
	}
    }
}
