#!/usr/bin/perl

package MY_PACKAGE;
use strict;
sub getint;
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 $card = shift;
if(!defined $card) { 
    $card = getint "Enter card number (0-7): ";
}

if($card eq "all") {
    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/) {
		    foreach my $dom ('A'..'B') {
			print "$card $pair $dom: ";
			my $isresp = `cat $procdir/card$card/pair$pair/dom$dom/is-communicating`;
			print $isresp =~ "is communicating"?"communicating":"NOT communicating";
			print "\n";
		    }
		}
	    }
	}
    }
    exit;
}


my $pair = shift;
if(!defined $pair) {
    $pair = getint "Enter wire pair number (0-3): ";
}

# my $aorb = shift;
# if(!defined $aorb) {
#     $aorb = getint "Enter DOM number (0-1): ";
# }

# if($aorb eq "a" || $aorb eq "A") { 
#     $aorb = 0;
# } elsif ($aorb eq "b" || $aorb eq "B") {
#     $aorb = 1;
# }

# if($aorb ne "0" && $aorb ne "1") {
#     die "DOM Number must be 0 or 1 (or A or B) (you gave $aorb)\n";
# }

my $pf = "$procdir/card".$card."/pair".$pair."/pwr";
open PF, ">$pf";
print PF "on";
close PF;

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__

