#!perl

use strict;
use warnings;
use Test::More;

# This script tests whether the scripts in the "examples" directory do print
# what they should print.

BEGIN {
    # Several arguments for open, "-|" needed.
    # This will only work on non-windows, perl >= 5.8.0
    # Update: Now I trick around that, thus making it work on perl 5.6.  Dunno
    # if it works on windows though.
    $^O =~ /MSWin32/i
        and plan skip_all => 'This test requires an operating system.';
    #local $@;
    #eval 'use 5.008_000; 1'
    #    or plan skip_all => "This test won't work on your perl version.";
}

use File::Spec;

my $exampledir = 'examples';
if (! -d $exampledir) {
    $exampledir = File::Spec->catfile('..', $exampledir);
}

my @examples = <$exampledir/*.pl>;

die "No examples found in $exampledir." unless @examples;

plan tests => scalar(@examples);

for my $example (@examples) {
    # Won't work on perl 5.6:
    # open my $pipe, '-|', $^X, $example
    #     or die "run $example: $!";

    my $pid = open my $pipe, '-|';
    die $! unless defined $pid;
    if (0 == $pid) {
        exec ($^X, $example);
        die $!;
    }

    my $output = do {local $/; <$pipe>};
    die $! unless defined $output;
    close $pipe or die "$example: exited $?";
    open my $examplefh, '<', $example or die "open $example: $!";
    my $content = do {local $/; <$examplefh>};
    defined $content or die "read $example: $!";
    my ($expected_output) = $content =~ /^Output:\s*^(.*)\Z/ms
        or die "$example corrupt";

    for ($output, $expected_output) {
        # The bitmask is not portable
        s/^bitmask:.*//m;

        # hints and hinthash depend on the perl version
        s/^hint.*//mg;

        # Avoid any newline problems
        $_ = join "\n", m{[^\015\012]+}g;
    }

    is($output, $expected_output, $example);
}
