#!/bin/bash

########################################################################
# vmnotify - An Asterisk-VoiceMail compatible MWI notification script
# (c) 2007 Sipwise. All rights reserved.
#
# Author: Andreas Granig <agranig@sipwise.com>
#
# Usage: vmnotify <context> <user> <messages>
#
########################################################################


CONFFILE="/etc/ngcp-vmnotify/vmnotify.conf"
LOGGER="/usr/bin/logger -i -t vmnotify"

function debug
{
	LOG_ARGS="-p daemon.debug"
	if [ "x$CONSOLE_DEBUG" = "x1" ]; then 
		LOG_ARGS="$LOG_ARGS -s"
	fi
	echo "$@" | $LOGGER $LOG_ARGS
}

function error
{
	LOG_ARGS="-p daemon.err"
	if [ "x$CONSOLE_DEBUG" = "x1" ]; then 
		LOG_ARGS="$LOG_ARGS -s"
	fi
	echo "$@" | $LOGGER $LOG_ARGS
	exit 1
}


test -f $CONFFILE || error "Config file not found"
. $CONFFILE

test -f $SIPSAK || error "sipsak command not found"
test -f $UUIDGEN || error "uuidgen command not found"


debug "Arguments: $@"

if [ "x$SERVER" = "x" ]; then
	error "Config parameter SERVER not specified"
fi

CONTEXT=$1
USER=$2
MESSAGES=$3

if [ "x$CONTEXT" = "x" ]; then
	error "Usage: $0 <context> <cli> <messages>"
fi
if [ "x$USER" = "x" ]; then
	error "Usage: $0 <context> <cli> <messages>"
fi
if [ "x$MESSAGES" = "x" ]; then
	error "Usage: $0 <context> <cli> <messages>"
fi

URI="sip:$USER@$SERVER"

if [ "x$MESSAGES" = "x0" ]; then
	MW="no"
else
	MW="yes"
fi

NEW=$MESSAGES
OLD="0" # asterisk doesn't send number of old messages!

BODY_MW="Messages-Waiting: $MW"
BODY_VM="Voice-Message: $NEW/$OLD"
BODYLEN=$((${#BODY_MW}+2+${#BODY_VM}+2))
CALL_ID=$($UUIDGEN)@voip.sipwise.local
MBID=$USER
BRANCH=$($UUIDGEN)

nohup $SIPSAK -S -i -k $LOCAL_IP -l 5081 -f $SIPFILE \
	-G -g "!BODY_MW!$BODY_MW!BODY_VM!$BODY_VM!BODYLEN!$BODYLEN!CALL_ID!$CALL_ID!MBID!$MBID!BRANCH!$BRANCH!" \
	$VERBOSE -E udp -s $URI 1>/dev/null 2>/dev/null &
