#!/usr/bin/perl

# Transform Makefile.am and config.in so they can be executed
# standalone. Then run the test suite.

# There should be a way to use m4 for this.

use 5.010;
use strict;
use warnings;

use Config;
use Cwd;

my $big_endian = sub {
    my $bo = $Config{'byteorder'};
    ($bo == 87654321) and return 1;
    ($bo == 12345678) and return;
    die ("Cannot understand byte order: $bo");
}->();

chdir ('test') or die ("Cannot change to test/: $!");

my $PWD = getcwd;

sub transform {
    my ($src_file, $dst_file) = @_;

    my $fh_in;
    my $fh_out;
    open ($fh_in, '<', $src_file) or
        die ("Cannot open '$src_file': $!");
    open ($fh_out, '>', $dst_file) or
        die ("Cannot write '$dst_file': $!");

    my $in_clause;
    my $mute;
    while (defined (my $line = <$fh_in>)) {
        if ($line =~ /if WORDS_BIGENDIAN/) {
            $in_clause and die ('State machine error');
            $in_clause = 1;
            $mute = !$big_endian;
            next;
        } elsif ($line =~ /^else/) {
            $in_clause or die ('State machine error');
            $mute = $big_endian;
            next;
        } elsif ($line =~ /^endif/) {
            $in_clause or die ('State machine error');
            $mute = undef;
            $in_clause = undef;
            next;
        }

        $mute and next;

        $line =~ s/\@PRINTF\@/printf/;
        $line =~ s/\@host\@/localhost/;
        $line =~ s/\@(target|build|nic1|nic2)\@/'-$1-'/;
        $line =~ s:=../src/:=/usr/bin/:;
        $line =~ s/\@debug_run_time_flag\@/--dbug=1/;
        $line =~ s/^(all: .+) tcpreplay (.+)$/$1 $2/;
        $line =~ s/\@srcdir\@/$PWD/g;
        print $fh_out $line;
    }
    close ($fh_in);
    close ($fh_out) or die;

    system ('diff', '-u', $src_file, $dst_file);
}

transform ('Makefile.am', 'Makefile.test');
transform ('config.in', 'config');

$ENV{'srcdir'} = $PWD;
system ('make', '-f', 'Makefile.test');
my $exit = $? ? 1 : 0;

print "test.log content:\n";
system ('cat', 'test.log');

exit $exit;

__END__
