#!/usr/bin/perl

use strict;
use Socket;

my $mgrUSERNAME = 'setthis';
my $mgrSECRET = 'setthis';
my $server_ip = '127.0.0.1';

sub error {
	my ($m) = @_;

	print STDERR "Error occured: ", $m, "\n";
	exit 1;
}

my $proto = getprotobyname("tcp");
my $paddr = sockaddr_in(5038, inet_aton("127.0.0.1"));
unless (socket(S, PF_INET, SOCK_STREAM, $proto)) {
	error("Could not create socket");
}
unless (connect(S, $paddr)) {
	close S;
	error("Could not connect to manager: " . $!);
}

my $line = <S>;
unless ($line =~ /Asterisk Call Manager/) {
	close S;
	error("Unexpected response from manager");
}

select S;
$| = 1;
print "Action: Login\r\nUsername: ", $mgrUSERNAME, "\r\nSecret: $mgrSECRET\r\n\r\n";

my $r = get_response(0);

sub get_response {
	my ($long_flag) = @_;
	my $result = {};
	my $line;
	my $longmode = 0;

	while ($line = <S>) {
		if ($longmode) {
			if ($line eq "--END COMMAND--\r\n") {
				$longmode = 0;
			} else {
				$result->{''} .= $line;
			}
		} else {
			if ($line eq "\r\n") {
				return $result;
			} elsif ($line =~ /^([^:]+):\s(.*)\r\n$/) {
				$result->{$1} = $2;
				if (($1 eq 'Response') && ($2 eq 'Follows') && $long_flag) {
					$result->{''} = "";
					$longmode = 1;
				}
			}
		}
	}
}

if ($r->{Response} ne 'Success') {
	close S;
	error("Could not log in to manager");
}

print "Action: Originate\r\nChannel: Local/conf-",
	$ARGV[0], "\@confhelper/n\r\nExten: ",
	$ARGV[1],
	"\r\nContext: confhelper\r\nPriority: 1\r\n\r\n";

my $got = get_response(0);

print "Action: Logoff\r\n\r\n";

$r = get_response(0);

close S;
select STDOUT;
