#!/usr/bin/perl
# -*- mode: perl; perl-indent-level: 2; -*-

# diff-file-output-by-test

# diff the 2 file arguments

# printing an error message if a difference
# else printing a success message.
# used in trivial test suites

# TBD: grep out stuff that "may vary between test runs"

# TBD: make it usable as a tee like command, accepting stdin

# TBD: optionally print diff

# TBD: infer filename

use strict;
use POSIX;


main();
die "should be unreachable - main should have exited";

sub main {

  my $tee;

  if( $ARGV[0] eq "-tee" ) {
    shift @ARGV;
    $tee = 1;
  }

  my $file0 = $ARGV[0];
  my $file1 = $ARGV[1];
  # TBD: should I say which is expected, and which not?

  my $cleanup = 1;


  if( ! defined $file1 ) { $file1 = "$file0-expect"; }

  if( $tee ) {
    unlink $file0;
    die "tee: output file could not be deleted: $file0" if -e $file0;
    system("tee $file0");
    die "tee: output file not created: $file0" if !-e $file0;
  }
  
  die "error: file does not exist: $file0" if ! -e $file0;
  die "error: file does not exist: $file1" if ! -e $file1;
  
  my $tmp_file0 = grep_out_stuff_that_may_vary_between_runs($file0);
  my $tmp_file1 = grep_out_stuff_that_may_vary_between_runs($file1);
  

  print "DIFFing $file0 $file1\n";
  my $system_command = "diff -C 10 $tmp_file0 $tmp_file1";
  my $ret = system($system_command);
  
  
  if( POSIX::WIFEXITED($ret) ) {
    my $wexit = POSIX::WEXITSTATUS($ret);
    if( 0 == $wexit ) {
      print "TEST PASSED (no diffs): $file0 $file1\n";
      if( $cleanup ) {
	unlink $tmp_file0 || warn "cleanup failed: could not unlink: $tmp_file0";
	unlink $tmp_file1 || warn "cleanup failed: could not unlink: $tmp_file1";
      }
      exit(0);
      
    } 
    elsif( 1 == $wexit ) {
      print "TEST FAILED (diffs found): $file0 $file1\n";
      exit(1);
    }
    else {
      print "TEST FAILED (diff failed to run): return status = $wexit: $file0 $file1\n";
      exit(1);
    }
  }
}


sub grep_out_stuff_that_may_vary_between_runs {
  my $file = shift;

  my $result_file = "$file.grep_out_stuff_that_may_vary_between_runs";

  die "error: file does not exist: $file" if !-e $file;
  
  unlink($result_file);
  die "error: could not remove existing result_file: $result_file" if -e $result_file;
  

  system("cat <$file "
	 . "| grep -v -e '^Date:' "
	 . "| grep -v -e '^Stuff-that-mat-vary-between-runs:' "
	 . "> $result_file");
  # TBD: remove other stuff?
  # TBD: remove XML clauses?
  die "error: did not create result_file: $result_file" if !-e $result_file;

  return $result_file;
}
