#!/usr/local/bin/perl

# enable/disable Message Waiting Light via SIP
# mwi.pl v20100730.01
# Copyright 2010 Jeremy Kister

use strict;
use IO::Socket::INET;
use Sys::Hostname;
use Getopt::Std;

my %opt;
getopts('m:h:x:', \%opt);

die "specify -m <mode> (on|off)\n" unless($opt{m} =~ /^(?:on|off)$/);
die "specify -h <host> -x <xtn>\n" unless($opt{h} && $opt{x});

my $me = join( '.', unpack('W4', gethostbyname( hostname() )) );

die "couldnt gethostbyname\n" unless($me);

my $mw = ($opt{m} eq 'on') ? 'yes' : 'no';
my $vm = ($opt{m} eq 'on') ? '0/0 (0/0)' : '1/0 (1/0)';
my $payload = <<EOBODY
Messages-Waiting: ${mw}
Message-Account: sip:mwi\@${me}
Voice-Message: ${vm}
EOBODY
;

my $body = join("\r\n", split(/\n/, $payload));
my $len = length($body);

my $data = <<EODATA
NOTIFY sip:$opt{x}\@$opt{h}:5060;transport=udp SIP/2.0
Via: SIP/2.0/UDP ${me}:5060;branch=z9hG4bK311d9r9e;rport
Max-Forwards: 70
From: "asterisk" <sip:mwi\@${me}>;tag=as2618af65
To: <sip:$opt{x}\@$opt{h}:5060;transport=udp>
Contact: <sip:mwi\@${me}>
Call-ID: 38f7ff684df0f4e43f18825d4217b5ee\@${me}
CSeq: 102 NOTIFY
User-Agent: mwi.pl v20100730.01
Event: message-summary
Content-Type: application/simple-message-summary
Content-Length: ${len}

${payload}
EODATA
;

my $packet = join("\r\n", split(/\n/, $data));

my $sock = IO::Socket::INET->new(PeerAddr => $opt{h},
        	 		 PeerPort => 5060,
				 Proto    => 'udp',
				 Timeout  => 1)
	|| die "cannot setup sock: $!\n";

print $sock $data;
