#!/usr/bin/perl
BEGIN {
    use File::Spec::Functions qw(rel2abs);
    use File::Basename qw(dirname);
    my $path   = rel2abs( $0 );
    our $directory = dirname( $path );
}
use lib $directory;
use strict;
use warnings;
use RFC::Main;
use RFC::Rig;
print "Writing test script for all rigs on this server....\n";


my $file = 'test.t';
open MYOUT,'>',$file or die "Could not open file $file for writing $!\n";
print MYOUT "#!/usr/bin/perl\n";
print MYOUT <<END;

BEGIN {
    use File::Spec::Functions qw(rel2abs);
    use File::Basename qw(dirname);

    my \$path   = rel2abs( \$0 );
    our \$directory = dirname( \$path );
}

use lib \$directory;

END

unless (-d '/home/celltest' )
{
    print MYOUT "use Test::Simple tests=>2;\n";
    print MYOUT "use SemaforeFile;\n";
    print MYOUT "my \$r = undef;\n";
    print MYOUT "my \$file = SemaforeFile->new('dummy.txt');\n";
    print MYOUT "ok(defined(\$file) && ref(\$file) eq 'SemaforeFile','new() works for semaforeFile');\n";
    print MYOUT "ok(\$file->readlines() == 0,\"testing that the file 'dummy.txt' contains no data\");\n";
    close MYOUT;
    exit;
}


my @rigs = RFC::Main::get_rigs();
my $nr = 2;
foreach my $rig (@rigs)
{
    print "Writing script for rig $rig\n";
    my $r = RFC::Rig->new($rig);
    my @l = $r->test_list();
    $nr++;
    $nr++;
    $nr++;
    $nr += @l;
}

print MYOUT "use Test::Simple tests=>$nr;\n";
print MYOUT "use RFC::Rig;\n";
print MYOUT "use SocketClient;\n";
print MYOUT "SocketClient::timeout(0);\n";
print MYOUT "my \$file = SemaforeFile->new('dummy.txt');\n";
print MYOUT "ok(defined(\$file) && ref(\$file) eq 'SemaforeFile','new() works for semaforeFile');\n";
print MYOUT "ok(\$file->readlines() == 0,\"testing that the file 'dummy.txt' contains no data\");\n";
print MYOUT "\n";

foreach my $rig (@rigs)
{
    print MYOUT 'print "###########   Testing rig '.$rig.' #########\n";',"\n";
    print MYOUT '$r = RFC::Rig->new(',$rig,');',"\n";
    print MYOUT "ok(defined(\$r) && ref(\$r) eq 'RFC::Rig','new() works for rig $rig');\n";
    print MYOUT "ok(\$r->error eq '','Init returned no errors');\n";
    print MYOUT "\n";
    print MYOUT 'my @list = $r->test_list();',"\n";
    print MYOUT 'foreach my $item (@list)',"\n";
    print MYOUT "{\n";
    print MYOUT "    eval {\n";
    print MYOUT '        ok($$item{"id"}->test(),$$item{"name"});',"\n";
    print MYOUT "    };\n";
    print MYOUT "    if (\$\@)\n";
    print MYOUT "    {\n";
    print MYOUT "        print \"ERROR: Test for \$\$item{'name'} died!\";\n";
    print MYOUT "        print \$\@;\n";
    print MYOUT "    }\n";
    print MYOUT "}\n";
    print MYOUT 'my @l = split(/[\s\t]+/,$r->readstring());',"\n";
    print MYOUT 'ok(@l%4 == 0,"Redstring contains modulo 4 rows");',"\n";
    print MYOUT "\n";
}
print MYOUT '$r->DESTROY() if ($r);',"\n";
print MYOUT "\n";
close MYOUT;
