#!/usr/bin/perl

# Convergence OpenPBX Tools Version 7.0 : AGI
# (c) MMII Convergence. All rights reserved.
# <info@convergence.pk> http://www.convergence.pk

# This program is free software, distributed under the terms of
# the GNU General Public License.http://www.gnu.org/licenses.html

use warnings;
use strict;

use Net::Telnet;

my $debug = 1;
my $agent = $ARGV[0];

if (!$agent) { $agent = "5.."; }
print "cPOP v 0.1 : match for =~ $agent\n";

my $host = '127.0.0.1';
my $user = 'cpop';
my $pass = 'manman';

my $t = new Net::Telnet (Port => 5038,
						Prompt => '/.*[\$%#>] $/',
						Output_record_separator => '',);
$t->open("$host");
$t->waitfor('/Asterisk Call Manager.*/');
$t->print("Action: Login\nUsername: $user\nSecret: $pass\n\n");

my ($prematch, $match) = $t->waitfor ("/Message: .*/");

if (($prematch =~ m/Success/) && ($match =~ m/Authentication/)) {
	&perr("authenticated, now monitoring ...");
} else {
	&perr("authentication failed, bye.");
	exit 1;
}  

while ($host) {
	$t->waitfor(match => '/Event: Bridge/', timeout => 7200);
	($prematch, $match) = $t->waitfor(match => '/Channel1: .*/', timeout => 1);
	&perr("Got bridge $match");
	if ($match !~ m/Channel1: SIP\/5..-*/) {
		&perr("Got external $match");
		($prematch, $match) = $t->waitfor(match => '/Channel2: .*/', timeout => 1);
		if ($match =~ m/Channel2: SIP\/$agent-.*/) {
			&perr("Got Agent on $match");
			($prematch, $match) = $t->waitfor(match => '/CallerID1: ....*/', timeout => 1);
			if ($match =~ m/CallerID1: (....*)/) {
				my $url = "firefox http://127.0.01/somescript.php?CLI=$1";
				&perr("Using $url");
				system ($url) or print STDERR "couldn't exec : $!\n";
			}
		} else {
			&perr("Not a call to $agent on $match");
		} 
	} else {
		&perr("Internal call by some agent $match");
	}
}

&perr("grr... should never reach here");
exit 1;

sub perr {
	my $line = shift(@_);
	print localtime() . " $line\n" if $debug;
}
