# Set defaults
# NOTE: (1) TP_HOME=.. works if tprocessor.cmd is started from the bin directory.
#           Otherwise, set TP_HOME to point to the TProcessor installation directory, or use 
#           the -home argument

$TP_HOME="..";
$PAR="";
if ($^O eq "MSWin32") {
  $PD="\\";
} else {
  $PD="/";
}

# Process parms
while (@ARGV && ($_ = $ARGV[0])){
  $_ =~ tr/\//-/;	# allow slash as option identifier
  if ($_ eq "-?" || $_ eq "-h" || $_ eq "-help") {usage(); exit();} 
  elsif ($_ eq "-home") {shift; $TP_HOME=$ARGV[0];}
  elsif ($_ eq "-infile") {shift; $ER_INFILE=$ARGV[0];}
  elsif ($_ eq "-outfile") {shift; $ER_OUTFILE=$ARGV[0];}
  else {$PAR="$PAR $_";}
  shift;
}
# Invoke the report
$OPTS="-Dxdav.home=\"$TP_HOME\" -Xms100M -Xmx200M";

if (!$ER_INFILE) {
  $ER_INFILE="-infile $TP_HOME"."$PD"."testsuite"."$PD"."junit"."$PD"."testCasesResults.xml";
}
if (!$ER_OUTFILE) {
  $ER_OUTFILE="-outfile $TP_HOME"."$PD"."testsuite"."$PD"."junit"."$PD"."testErrorsReport.txt";
}
cpbuild("$TP_HOME"."$PD"."lib");

$CLS="org.apache.slide.testsuite.testtools.tprocessor.TErrorsReport $ER_INFILE $ER_OUTFILE";
$JH=$ENV{"JAVA_HOME"};
$CMD="$JH"."$PD"."bin"."$PD"."java";
print ("$CMD $OPTS $CLS $PAR\n");
system ("$CMD $OPTS $CLS $PAR");

sub usage {
print <<EOU;

Usage: terrorsreport [options] 

Options:
  -infile <testsuite_result_xml>     (default: %TP_HOME%\testsuite\junit\testcasesresults.xml)
  -outfile <errors_report>           (default: %TP_HOME%\testsuite\junit\errors.txt;
                                         also allowed: stdout, stderr)

EOU
 ;
}

sub cpbuild {
  my $path=$_[0];
  my $CP="";
  print "Appending $path and all jar files contained in $path to the classpath...\n\n";

  my $SEP=":";
  if ($^O eq "MSWin32") {
     $SEP=";";
  }
  my $wrk=$ENV{"CLASSPATH"};
  $ENV{"CLASSPATH"}=$wrk.$SEP.$path;
  opendir (JD, "$path") || die "Cannot open $path";
  foreach (readdir(JD)) {
    next if (substr($_, length($_) - 4, length($_)) ne ".jar");
    if (!$CP) {$CP=$path.$PD.$_}
    else {$CP=$CP.$SEP.$path.$PD.$_}
  }
  $ENV{"CLASSPATH"}=$ENV{"CLASSPATH"}.$SEP.$CP;
  closedir JD;
}

