#!/usr/bin/perl -w

use Data::Dumper;
our $ifcount = 31;
our $media = "E1";
our $dchan = 16;
sub proc_args(@)
{
	while($bit = shift @ARGV){
		if ($bit =~ /-m/){
			my $m = shift @ARGV;
			if ($m =~ /t1/i){
				$ifcount = 24;
				$media = "T1";
				$dchan = 24;
			}
		}
	}
}

sub get_cards()
{
	$lspci = "/sbin/lspci -nd 1923:0300";
	@pcibus = `$lspci`;
	my $cc=0;
	my @junk;
	foreach $line (@pcibus){
		$cc++;
		@card = split(" ",$line);
		($bus,$slotq)=split(":",$card[0]);
		($slot,@junk) = split(/\./,$slotq);
		$bus = 0 + $bus;
		$slot = hex($slot);
		$cards->{$cc}{num}=$cc;
		$cards->{$cc}{bus}=$bus;
		$cards->{$cc}{slot}=$slot;
		$cards->{$cc}{ifcount}=$ifcount;
		$cards->{$cc}{media}=$media;
		$cards->{$cc}{dchan}=$dchan;
		$cards->{$cc}{name}="wanpipe$cc";
	}
	return ($cc,$cards);
}

sub gen_devices($)
{
	my $devcount = shift || 0;
	print "[devices]\n";
	for ($i=1;$i<=$devcount;$i++){
		print "wanpipe$i = WAN_AFT, Comment\n";
	}
	print "\n";
}

sub gen_interfaces($)
{
	my $devhash = shift || 0;
	print "[interfaces]\n";
	foreach $bit (keys %{$devhash}){
		my $dev = $devhash->{$bit};
		for ($i=1;$i<=$dev->{ifcount};$i++){
			print "wp".$dev->{num}."aft".$i." = ".$dev->{name}.", auto, API, Comment\n";
		}
	}
	print "\n";
}

sub gen_cards($)
{
	my $devhash = shift || 0;
	foreach $bit (keys %{$devhash}){
		my $dev = $devhash->{$bit};
		print "[".$dev->{name}."]\n";
		print "CARD_TYPE         = AFT\n";
		print "S514CPU           = A\n";
		print "AUTO_PCISLOT      = NO\n";
		print "PCISLOT           = ".$dev->{slot}."\n";
		print "PCIBUS            = ".$dev->{bus}."\n";
		print "MEDIA             = ".$dev->{media}."\n";
		if ($dev->{media} =~ /e1/i){
		print "LCODE             = HDB3\n";
		print "FRAME             = CRC4\n";
		}
		else {
		print "LCODE             = B8ZS\n";
		print "FRAME             = ESF\n";
		}
		print "TE_CLOCK          = NORMAL\n";
		print "ACTIVE_CH         = ALL\n";
		print "Firmware          = /etc/wanpipe/firmware/cdual514.sfm\n";
		print "Interface         = V35\n";
		print "Clocking          = External\n";
		print "BaudRate          = 1540000\n";
		print "MTU               = 1500\n";
		print "UDPPORT           = 9000\n";
		print "TTL               = 255\n";
		print "IGNORE_FRONT_END  = NO\n";
		print "\n";
#TE_ACTIVE_CH    = ALL
#TE_LBO          = 0DB
#TE_HIGHIMPEDANCE        = NO

	}
}
sub gen_slots($)
{
	my $devhash = shift || 0;
	foreach $bit (keys %{$devhash}){
		my $dev = $devhash->{$bit};
		for($i=1;$i<=$dev->{ifcount};$i++){
			print "[wp".$dev->{num}."aft".$i."]\n";
			print "ACTIVE_CH       = $i\n";
			if ($dev->{dchan} == $i){
				print "HDLC_STREAMING  = YES\n";
			}
			else {
				print "HDLC_STREAMING  = NO\n";
				print "IDLE_FLAG       = 0x7E\n";
				print "MTU             = 160\n";
				print "MRU             = 160\n";
			}
			print "\n";
		}
	}
}

proc_args(@ARGV);
my ($count,$cards) = get_cards();
gen_devices($count);
gen_interfaces($cards);
gen_cards($cards);
gen_slots($cards);
