package Zaptel::Chans;
#
# Written by Oron Peled <oron@actcom.co.il>
# Copyright (C) 2007, Xorcom
# This program is free software; you can redistribute and/or
# modify it under the same terms as Perl itself.
#
# $Id: Chans.pm 5177 2007-12-24 20:31:24Z tzafrir $
#
use strict;
use Zaptel::Utils;

sub new($$$$$$) {
	my $pack = shift or die "Wasn't called as a class method\n";
	my $span = shift or die "Missing a span parameter\n";
	my $line = shift or die "Missing an input line\n";
	my ($num, $fqn, $rest) = split(/\s+/, $line, 3);
	$num or die "Missing a channel number parameter\n";
	$fqn or die "Missing a channel fqn parameter\n";
	my $signalling = '';
	if(defined $rest && ($rest =~ s/(\w+)//)) {
		$signalling = $1;
	}
	my $info = '';
	if(defined $rest && ($rest =~ s/(.*)//)) {
		$info = $1;
	}
	my $self = {};
	bless $self, $pack;
	$self->{SPAN} = $span;
	$self->{NUM} = $num;
	$self->{FQN} = $fqn;
	$self->{SIGNALLING} = $signalling;
	$self->{INFO} = $info;
	my $type;
	if($fqn =~ m|\bXPP_(\w+)/.*$|) {
		$type = $1;		# One of our AB
	} elsif ($fqn =~ m{\bFXS/.*}) {
		$type = "FXS"; # likely Rhino
	} elsif ($fqn =~ m{\bFXO/.*}) {
		$type = "FXO"; # likely Rhino
	} elsif ($fqn =~ m{\b---/.*}) {
		$type = "EMPTY"; # likely Rhino, empty slot.
	} elsif ($fqn =~ m{\b(TE[24]|WCT1|Tor2|TorISA|WP[TE]1|cwain[12])/.*}) {
		# TE[24]: Digium wct4xxp
		# WCT1: Digium single span card drivers?
		# Tor2: Tor PCI cards
		# TorISA: ISA ones (still used?) 
		# WP[TE]1: Sangoma. TODO: this one tells us if it is TE or NT.
		# cwain: Junghanns E1 card.
		$type = "PRI";
	} elsif ($fqn =~ m{\b(ZTHFC%d*|ztqoz\d*)/.*}) {
		# ZTHFC: HFC-s single-port card (zaphfc/vzaphfc)
		# ztqoz: qozap (Junghanns) multi-port HFC card
		$type = "BRI";
	} elsif ($fqn =~ m{\bztgsm/.*}) {
		# Junghanns GSM card
		$type = "GSM";
	} elsif(defined $signalling) {
		$type = 'FXS' if $signalling =~ /^FXS/;
		$type = 'FXO' if $signalling =~ /^FXO/;
	} else {
		$type = undef;
	}
	$self->type($type);
	$self->span()->type($type)
		if ! defined($self->span()->type()) ||
			$self->span()->type() eq 'UNKNOWN';
	return $self;
}

my $ztcfg = $ENV{ZTCFG} || '/sbin/ztcfg';
sub probe_type($) {
	my $self = shift;
	my $fqn = $self->fqn;
	my $num = $self->num;
	my $type;

	if($fqn =~ m:WCTDM/| WRTDM/|OPVXA1200/:) {
		my %maybe;

		undef %maybe;
		foreach my $sig (qw(fxo fxs)) {
			my $cmd = "echo ${sig}ks=$num | $ztcfg -c /dev/fd/0";

			$maybe{$sig} = system("$cmd >/dev/null 2>&1") == 0;
		}
		if($maybe{fxo} and $maybe{fxs}) {
			$type = 'EMPTY';
		} elsif($maybe{fxo}) {
			$type = 'FXS';
		} elsif($maybe{fxs}) {
			$type = 'FXO';
		} else {
			$type = 'EMPTY';
		}
	} else {
		$type = $self->type;
	}
	return $type;
}

1;
