#! /usr/bin/env perl
##**************************************************************
##
## Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
## University of Wisconsin-Madison, WI.
## 
## Licensed under the Apache License, Version 2.0 (the "License"); you
## may not use this file except in compliance with the License.  You may
## obtain a copy of the License at
## 
##    http://www.apache.org/licenses/LICENSE-2.0
## 
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
##**************************************************************

use strict;
use warnings;

die "usage: run_cpuinfo_tests <cpuinfo file>" if ( $#ARGV < 0 );
my $CpuInfoFile = shift;

# First pass: count the # of UNAME entries
my $NumUnames = 0;
open( IN, $CpuInfoFile ) or die "Can't read $CpuInfoFile";
while(<IN>)
{
    chomp;
    if( /^UNAME:(.*)/ )
    {
	$NumUnames++ if ( defined($1) and ( $1 ne "" ) );
    }
}
close(IN);
die "Can't find any CPU entries" if ( $NumUnames <= 0 );
print "Found $NumUnames entries\n";

my @Failed;
foreach my $i ( 1 .. $NumUnames )
{
    my $Cmd = "./condor_sysapi --cpuinfo_file $CpuInfoFile $i";
    my $Passed = 0;
    my $Failed = 0;
    my $Error = 0;
    my $Line = -1;
    my $Uname;
    my $Summary = "";
    open( TEST, "$Cmd 2>&1 |" ) or die "Can't run '$Cmd'";
    while( <TEST> )
    {
	chomp;
	if ( /line (\d+):/ )
	{
	    $Line = $1;
	}
	elsif ( /^linux/i )
	{
	    $Uname = $_;
	}
	elsif ( /SysAPI: (Detected.*)/ )
	{
	    $Summary = $1;
	}
	elsif ( /Passed/ )
	{
	    $Passed++;
	}
	elsif ( /SysAPI\/Linux:/ )
	{
	    $Error++;
	}
    }
    close( TEST );
    $Failed = !$Passed;
    printf
	"%03d %5d %-60.60s\n  %s\n  %s\n",
	$i, $Line, $Uname,
	$Summary,
	( $Failed ? "FAILED" : ($Error ? "ERROR" : "PASSED" ) );

    push( @Failed, $i ) if ( not $Passed or $Error);
}

print "\n\n" . scalar(@Failed) . " tests failed\n\n";

foreach my $i ( @Failed )
{
    print "\nTest $i failed -- re-running with FULLDEBUG\n";

    my $Cmd = "./condor_sysapi --cpuinfo_file $CpuInfoFile $i";
    $Cmd .= " --debug D_FULLDEBUG";
    open( TEST, "$Cmd 2>&1 |" ) or die "Can't run '$Cmd'";
    while( <TEST> )
    {
	print;
    }
    close( TEST );
    
}
