#!/usr/bin/perl

package MY_PACKAGE;
use strict;
sub getint;
sub usage { return <<EOF;
Usage: $0 all
       $0 <card0> <pair0> <card1> <pair1> ...
EOF
;
}

my $procdir = "/proc/driver/domhub";

my $fvers = `/usr/local/bin/fvers.pl`;
print $fvers;
if($fvers =~ /FFFF/) {
    print "FPGA on at least one card is messed up, please restore PCI config space & reload\n";
    print "(or reboot).\n";
}

my @cards;
my @pairs;
my $doall = 0;

while(1) {
    my $card = shift;
    if($card eq "all") { $doall++; last; }
    last unless defined $card;
    push @cards, $card;
    my $pair = shift;
    die usage unless defined $pair;
    push @pairs, $pair;
}
die usage unless (scalar @cards)==(scalar @pairs);
die usage unless $doall || (scalar @cards>0);

if(! $doall) {
    for(0..(@cards)-1) {
	my $pl = `cat /proc/driver/domhub/card$cards[$_]/pair$pairs[$_]/is-plugged`;
	die "Card $cards[$_] pair $pairs[$_] is NOT plugged in!\n" if($pl !~ /is plugged/);
    }

    print "Will power on: ";
    for(0..(@cards)-1) {
	print "card $cards[$_], pair $pairs[$_]".(($_ == (@cards)-1)?".\n":"; ");
    }
}

my $ncom = 0;

if($doall) {
    my $pf = "$procdir/pwrall";
    open PF, ">$pf" || die "Can't open $pf: $!\n";
    print PF "on";
    close PF;
    foreach my $card (0..7) {
	if(-e "$procdir/card$card") {
	    foreach my $pair (0..3) {
		my $procdata = `cat $procdir/card$card/pair$pair/is-plugged`;
		# print $procdata;
		if($procdata =~ /is plugged in/) {
		    my @doms = ('B','A');
		    foreach my $dom (@doms) {
			print "$card $pair $dom: ";
			my $isresp = `cat $procdir/card$card/pair$pair/dom$dom/is-communicating`;
			$ncom++ if $isresp =~ "is communicating";
			print $isresp =~ "is communicating"?"communicating":"NOT communicating";
			print "\n";
		    }
		}
	    }
	}
    }
    print "$ncom DOMs are communicating.\n";
    exit;
}

for(0..(@cards)-1) {
    my $card = $cards[$_];
    my $pair = $pairs[$_];
    my $pf = "$procdir/card".$card."/pair".$pair."/pwr";
    open PF, ">$pf";
    print PF "on";
    close PF;
}

for(0..(@cards)-1) {
    my $card = $cards[$_];
    my $pair = $pairs[$_];
    my $pfA = "$procdir/card".$card."/pair".$pair."/domA/is-communicating";
    my $pfB = "$procdir/card".$card."/pair".$pair."/domB/is-communicating";
    open PFA, "$pfA";
    my $astring = <PFA>; chomp $astring;
    close PFA;
    $astring = "NO proc file found!" if $astring eq "";
    print "A DOM result: $astring\n";
    
    open PFB, "$pfB";
    my $bstring = <PFB>; chomp $bstring;
    close PFB;
    $bstring = "NO proc file found!" if $bstring eq "";
    print "B DOM result: $bstring\n";
}

exit;
sub getint {
    my $s = shift; 
    while(1) {
	print $s;
	my $resp = <STDIN>;
	if($resp =~ /^(\d+)$/) {
	    return $1;
	}
    }
}


__END__

