package Dahdi::Config::Gen::Unicall;
use strict;

use Dahdi::Config::Gen qw(is_true);

sub new($$$) {
	my $pack = shift || die;
	my $gconfig = shift || die;
	my $genopts = shift || die;
	my $file = $ENV{UNICALL_CHANNELS_FILE} || "/etc/asterisk/unicall-channels.conf";
	my $self = {
			FILE	=> $file,
			GCONFIG	=> $gconfig,
			GENOPTS	=> $genopts,
		};
	bless $self, $pack;
	return $self;
}

sub generate($) {
	my $self = shift || die;
	my $file = $self->{FILE};
	my $gconfig = $self->{GCONFIG};
	my $genopts = $self->{GENOPTS};
	#$gconfig->dump;
	my @spans = @_;
	warn "Empty configuration -- no spans\n" unless @spans;
	die "Only for R2" unless $gconfig->{'pri_connection_type'} eq 'R2';
	rename "$file", "$file.bak"
		or $! == 2	# ENOENT (No dependency on Errno.pm)
		or die "Failed to backup old config: $!\n";
	print "Generating $file\n" if $genopts->{verbose};
	open(F, ">$file") || die "$0: Failed to open $file: $!\n";
	my $old = select F;
	printf "; Autogenerated by $0 on %s\n", scalar(localtime);
	print  "; If you edit this file and execute $0 again,\n";
	print  "; your manual changes will be LOST.\n";
	print  "; This file should be #included in unicall.conf\n\n";
	foreach my $span (@spans) {
		next unless $span->is_digital();
		printf "; Span %d: %s %s\n", $span->num, $span->name, $span->description;
		my $idle_bits = $gconfig->{'r2_idle_bits'}; 
		printf "protocolend=%s\n", ($span->termtype() eq 'TE') ? 'cpe' : 'co';
		printf "channel=%s\n", Dahdi::Config::Gen::bchan_range($span);
		print "\n";
	}
	close F;
	select $old;
}

1;

__END__

=head1 NAME

unicall - Generate configuration for unicall channels.

=head1 SYNOPSIS

 use Dahdi::Config::Gen::Unicall;

 my $cfg = new Dahdi::Config::Gen::Unicall(\%global_config, \%genopts);
 $cfg->generate(@span_list);

=head1 DESCRIPTION

Generate the F</etc/asterisk/unicall-channels.conf> to be included in 
F</etc/asterisk/unicall.conf>

Its location may be overriden via the environment variable 
C<UNICALL_CHANNELS_FILE>.
