#!/usr/bin/perl -w
use strict;
use lib 'lib';
use Mithraen::Sangoma::Fileutils;
use Mithraen::Sangoma::Template;

use vars qw/$VERSION $ABSTRACT/;
$VERSION  = '0.0.1';
$ABSTRACT = 'Create config files for Sangoma cards';

my $detect = shift;
my $path = shift || '/etc/wanpipe';
my %config;

sub get_template();

delete $ENV{PATH};
delete $ENV{ENV};

sub get_config($) {
	my $cfgfile = shift;
	my %config = %{ file_read_hash( $cfgfile )};
    $config{HWDCHAN} = $config{HWDCHAN} eq 'YES' ? 1 : 0;
    $config{HWDTMF}  = $config{HWDTMF}  eq 'YES' ? 1 : 0;
    {
        # master clock
        my $clock = $config{CLOCK} || "";
        my @clock = split ',', $clock;
        my %clock;
        local $_;
        $clock{$_} = 1 foreach @clock;
        $config{CLOCK} = \%clock;
    }
    $config{CLOCK} = "" unless defined $config{CLOCK};
	return %config;
}

%config = get_config($path."/config.txt");

sub get_hwprobe_text()
{
    my @arr;
    open( IN, "/sbin/service wanrouter hwprobe |" ) || die;
    while (<IN>) {
        push @arr, $_;
    }
    close(IN);
    return \@arr;
}

my $arr;
if ( defined $detect ) {
    $arr = file_read_arr($detect);
}
else {
	$arr = get_hwprobe_text();
}

my %cards;
my $card_i = 1;

my @configs;

foreach ( @{$arr} ) {
    next unless /^\s*(\d+)\s\.\s+([^\s]+)\s+:\s+(.+)$/;
    my $id  = $1;
    my $txt = $3;
    my @txt = split /\s*:\s*/, $txt;
    my %txt;
    foreach my $tmp (@txt) {
        $tmp =~ /^(.+?)=(.+)$/;
        $txt{$1} = $2;
    }
    my $card = $txt{BUS} . "|" . $txt{SLOT};
    $cards{$card} = $card_i++ unless defined( $cards{$card} );
    my $card_id = $cards{$card};

    #    print "$id,@txt";
    my $tpl = Mithraen::Sangoma::Template->get();
    $txt{ID}      = $id;
    $txt{DCHAN}   = $config{HWDCHAN} ? 16 : 0;
    $txt{HWDTMF}  = $config{HWDTMF} ? "TDMV_HW_DTMF = YES\n" : "";
    $txt{CARD_ID} = $card_id;
    $txt{CLOCK}   = $config{CLOCK}->{$id} ? "MASTER" : "NORMAL";
	$txt{TDMV_HWEC} = (defined $txt{HWEC} and $txt{HWEC} eq '128')? 'YES': 'NO';
	$txt{REF_CLOCK} = 1; # port from which we get master clock

    foreach my $key ( keys %txt ) {
        my $data = $txt{$key};
        $tpl =~ s/\#$key\#/$data/g;
    }
    file_write( "$path/wanpipe$id.conf", $tpl );
	push @configs, "wanpipe$id";
}

`sed -i 's/WAN_DEVICES=.*/WAN_DEVICES=\"@configs\"/' $path/wanrouter.rc 2>&1`;

