#!/usr/bin/env perl

use English;
use strict;
use warnings;
use open OUT => ":raw";

if ($#ARGV >= 0 && ($ARGV[0] eq '-h' || $ARGV[0] eq '--help')) {
   print <<END;

prediff-for-bsub-launcher is for the use with 'start_test' as
the system-wide prediff, when the launcher is bsub.
E.g. (assuming bash):

  CHPL_SYSTEM_PREDIFF=\$CHPL_HOME/util/test/prediff-for-bsub-launcher \\
    start_test ...

prediff-for-bsub-launcher assumes that the launcher prepends
to the test output three lines that start like this:

  Job XXX is submitted to
  <<Waiting for dispatch
  <<Starting on

If so, they are removed from the test output file.
Otherwise, the output file remains unchanged.

This script has the shortcoming of doing nothing if there is any
compiler diagnostics in a test. That's because the above three lines
no longer start the combined compiler+runtime output file.

END
exit();
}

### the files to operate on

# outfile is $2
my $outfile = $ARGV[1];
my $modfile = "$outfile.tmp";
open OUTFILE, $outfile or die "could not open the test output file $outfile: $!";

### check the first three lines
sub check1line {
   my ($pattern) = @_;
   my $line = <OUTFILE>;
   if (!$line || $line !~ /$pattern/) { nochange(); }
}

check1line('^Job .* is submitted to');
check1line('^<<Waiting for dispatch');
check1line('^<<Starting on');

### pass through the rest of the input directly
open MODFILE, ">$modfile" or die "could not open the modified test output file $modfile: $!";
while (<OUTFILE>) {
   print MODFILE $_;
}

### replace the old file with the new file
close(MODFILE) or die "could not close the modified test output file: $!";
close(OUTFILE) or die "could not close the test output file: $!";
system("mv $modfile $outfile");

exit();

### if there is no match, leave $outfile unchanged
sub nochange {
  close(OUTFILE);
  exit();
}
