#!/usr/bin/perl

###############################################################################
# Michael Jastremski
# Monitor Asterisk PBX via Manager Interface
# http://megaglobal.net/docs/
###############################################################################

# Based upon:
#
# TACI - Trivial Asterisk Call Interface v.02
# Last update 3/30/2004 
# Tony Wasson wasson@azxws.com
#

$ENV{'PATH'}='';
$ENV{'BASH_ENV'}=''; 
$ENV{'ENV'}='';
$| = 1; 

use Net::Telnet ();
use File::Basename;
use lib "/usr/local/opmon/libexec"; 
use utils qw(%ERRORS);

my $mgr_user = "admin";
my $mgr_secret = "chopp";
my $failed = 0;
my $reason = undef;
my ($server_ip) = @ARGV;

$tn = new Net::Telnet (Port => 5038,
		       Prompt => '/.*[\$%#>] $/',
		       Output_record_separator => '',
		       Errmode    => 'return'
		       );

$tn->open($server_ip);
$tn->waitfor('/0\n$/');                  	
$tn->print("Action: Login\nUsername: $mgr_user\nSecret: $mgr_secret\n\n");
unless($tn->waitfor('/Authentication accept*/'))
{
    $failed = 1;
    $reason = "Conexao Falhou";
}
else
{
    $tn->print("Action: Ping\n\n");
    unless($tn->waitfor('/Pong/'))
    {
	$failed = 1;
	$reason = "Ping nao respondeu";
    }
    else
    {
	$tn->print("Action: Logoff\n\n");
    }
}

print "OK - Asterisk PBX esta operacional\n" unless $failed;
print "CRITICAL - Nao consegue conectar ao Asterisk PBX ($reason)\n" if $failed;

exit $ERRORS{'CRITICAL'} if $failed;
exit $ERRORS{'OK'};


exit 0;

