#!/usr/bin/perl -w

use Net::Ping;
use Socket;
use HTTP::Date;

if ($#ARGV != 2) {
 print "usage: Polycom-check-sync.pl phone_ip sipserver_ip phone_extension\n";
 exit;
}


$phone = shift;
$sipserver = shift;
$extension = shift;

reboot_sip_phone( "$phone", "$sipserver", "$extension" );
exit(0); 

sub reboot_sip_phone {    # Send the phone a check-sync to reboot it
    $phone_ip = shift;

    $local_ip = shift;
    $sip_to   = shift;
    $sip_from = "asterisk";
    $tm       = time();
    $call_id  = $tm . "msgto$sip_to";
    $httptime = time2str();
    $MESG     = "NOTIFY sip:$sip_to\@$phone_ip:5060 SIP/2.0
Via: SIP/2.0/UDP $local_ip
From: <sip:$sip_from\@$local_ip>
To: <sip:$sip_to\@$phone_ip>
Event: check-sync
Date: $httptime
Call-ID: $call_id\@$local_ip
CSeq: 1300 NOTIFY
Contact: <sip:$sip_from\@$local_ip>
Content-Length: 0

";

print "Message to be sent:\n\n", $MESG, "\n\n";

    $proto = getprotobyname('udp');
    socket( SOCKET, PF_INET, SOCK_DGRAM, $proto );
    $iaddr = inet_aton("$phone_ip");
    $paddr = sockaddr_in( 5060, $iaddr );
    bind( SOCKET, $paddr );
    $port = 5060;

    $hisiaddr = inet_aton($phone_ip);
    $hispaddr = sockaddr_in( $port, $hisiaddr );

    if ( send( SOCKET, $MESG, 0, $hispaddr ) ) {
        print "check-sync sent to phone at ", "$phone_ip", "\n";
    }
    else { print "check-sync not sent to phone at $phone_ip\n", "failed...", "\n"; exit(1);}

}

