#! /usr/bin/perl

use Time::HiRes qw (usleep);

my $testgood = `modules/check_dir.pl | tail -1`;
if ( $testgood != 1 ) {
    printf("Strange directory.\n");
    printf("Please run this script only in Stand1 or Stand2 directory.\n");
    exit;
}

require "modules/read_setup.pl";

if( $#ARGV != 0 ) {
    printf("Please give tag number as argument.\n");
    system( "wing_showtags" );
    exit(0);
} else {
    $tag = $ARGV[0];
#    if ( ($tag < 1) || ($tag > 8) ) {
#	printf("Tag number should be >0 and <9.\n");
#	system( "wing_showtags" );
#	exit(0);
#    }
}

#$fee="TRD-FEE_2_0_0";


( $DIR_NAME, $DATE, $ROC_SERIAL, $ROC_LAYER, $ROC_TYPE, $DCS_SERIAL, $WITH_PIPES, $INITIAL, $TRD_FEE ) = read_setup();

$DATE = `/bin/date +%Y%m%d-%H%M`;
chop( $DATE );
printf("TRD_FEE = $TRD_FEE\n");

#printf("Changing cwd to $DIR_NAME\n");
#chdir( "$DIR_NAME" );


$testname = "unknown";
if    ( $tag ==  2 ) { $testname = "ce-ni"; }
elsif ( $tag ==  3 ) { $testname = "ce-ori"; }
elsif ( $tag ==  4 ) { $testname = "ce-bridge"; }
elsif ( $tag ==  5 ) { $testname = "ce-reset"; }
elsif ( $tag ==  6 ) { $testname = "ce-shutdown"; }
elsif ( $tag ==  7 ) { $testname = "ce-laser-ids"; }
elsif ( $tag ==  8 ) { $testname = "ce-nifast"; }
elsif ( $tag ==  9 ) { $testname = "ce-dmm"; }
elsif ( $tag == 10 ) { $testname = "ce-ddd"; }
elsif ( $tag == 11 ) { $testname = "ce-imm"; }
else                 { $testname = "unknown"; }

die "Unknown test" if $testname eq "unknown";

$pwd = `pwd`;
chop $pwd;

$logfile = "$pwd/_current/$testname-$DATE.log";
$logfile =~ s/^\/home\/trd//;


print  "Set logfile to $logfile\n";
system "pvss_inject ControlFero $TRD_FEE 'LOGFILE $logfile'";

sleep(1);

printf("Injecting tag=$tag to $TRD_FEE\n");
system( "pvss_inject ConfigureFero $TRD_FEE $tag" );
#sleep( 3 );


#flush STDOUT;
until ( -f $logfile ) {
    usleep (10000);
}

system "modules/ce_showlog.pl $logfile";

open( HF, ">> _current/_history" );
printf( HF "$DATE: Executed:ce_test.pl Logfile=%s\n", $logfile );
close( HF );

exit(1);

# EOF
