#!/usr/local/bin/perl -w

# run tests on invalid input
# usage:
#   tests.pl [<test number> [<test number> ...]]
#            [<script name> [<script name> ...]]

use strict;

use IPC::Open3;

use Test::More qw/ no_plan /;

my $num = 0;
my @tests;
{
  local $/ = '--- ';
  <DATA>;
  while (<DATA>) {
    chomp;
    my($label, $data) = split /\n/, $_, 2;
    $data or next;
    $num++;
    my($in, $out) = split /^--\n/m, $data;
    $out =~ s/\n$//;
    my $re = $out;
    push @tests, [$num, $label, $in, qr/$re/i];
  }
}

my @test_nums;
while (@ARGV and $ARGV[0] =~ /^\d+\z/) {
  my $num = shift(@ARGV) - 1;
  next if $num < 0 or $num > $#tests;
  push @test_nums, $num;
}

if (@test_nums) {
  @tests = @tests[@test_nums];
}

my @scripts;
if (@ARGV) {
  @scripts = @ARGV;
} else {
  @scripts = qw/ rjk roel xavier christian mjd2
                 rod adrian jurgen jean zsban /;
}

foreach my $script (@scripts) {
  if ($script !~ /\./) {
    if (-e "$script.pl") {
      $script .= '.pl';
    } elsif (-e "$script.ry") {
      $script .= '.ry';
    }
  }

  -e $script or do { warn "$script not found.\n"; next };

  my $cmd = 'perl';
  $cmd = 'ruby' if $script =~ /\.ry\z/;

  diag("** $script");

  local $/;

  foreach my $test (@tests) {
    my($num, $label, $in, $re) = @$test;

    open3(\*WTR, \*RDR, \*ERR, "$cmd $script");

    print WTR $in;
    close WTR;

    my $results = <RDR>;
    my $errors  = <ERR>;

    $results = '' if not defined $results;
    $errors  = '' if not defined $errors;

#    ok(!$errors, "$num $label STDERR");

    like("$errors\n$results", $re, "$num $label");
  }
}

__DATA__
--- 1-cycle
A 1 A
FINAL 0 A
--
circ|cycl|self
--- 2-cycle
A 1 B
B 1 A
C 1 B
FINAL 0 C
--
circ|cycl|unknown
--- 3-cycle
B 1 A
C 1 B
A 1 C
FINAL 0 C
--
circ|cycl|unknown
--- Repeated label
A 1
A 2
FINAL 0 A
--
duplicate|already|same
--- No FINAL
A 1
B 1 A
--
no.*FINAL|^\s*\z
--- Missing dependency
A 1
C 1 B
FINAL 0 C
--
missing|bad|not defined|unknown
--- END
