#!/usr/bin/perl

use Net::Ping;
use Socket; 

@gatekeepers = ( "192.168.22.254", "10.1.1.1" );

$port = 7001; 


sub check_gk {
  my($rhost) = @_;


    $connected = 1; 
    $gk=0;
    $ping =0;


    #workaround for silly linux 2.4.7
    $p = Net::Ping->new();
    $ping= $p->ping($rhost);
    $p->close();

    if ($ping)
    {

    $iaddr = inet_aton($rhost); 
    $paddr = sockaddr_in($port, $iaddr); 
    socket(SOCK, AF_INET, SOCK_STREAM, $proto) || die "socket: $!"; 
    connect(SOCK, $paddr) || {$connected=0};

#    print $connected;
    $i=0;

    while( <SOCK> ) { 
     $l=$_;
    # print $l;
     chomp ($l);
     $i++;
     if ( $i == 2 ) {last;};
    }

    $gk = ($l =~m/Gatekeeper/g);
#    print $gk;
    }
    else
    {
     print "Can't ping\n";
    }
    if ($connected && $gk )
    {
	 # gatekeeper is OK
#     print "Current GK is OK";
     return 1;
    }
    else
    {
     #problems with gatekeeper
     return 0;
    }
}


    #getting current GK
    #system('cat /etc/asterisk/ooh323.conf | awk \'{ if ($1=="gatekeeper") { print $3}; }\'');
    $rhost=qx(/usr/local/bin/get_ast_gk.sh);

    #checking it's status. if running-we exits :-)
    if ( check_gk($rhost) ) { exit 0; }
    
    #we are here if current gatekeeper is not available.
    #so we'll test which one is available and set it :-)
    
    
    foreach my $gatekeeper (@gatekeepers) {
	    if ( check_gk($gatekeeper) ) { print $gatekeeper; system ("/usr/local/bin/set_ast_gk.sh $gatekeeper"); exit 0;}
	}
    #if found working GK it is already set to it
    #if not- then not :-)
    
    
    