#!/bin/sh
# default IP address
GATEWAY_IP=192.168.1.1

po_domain="alterator-asterisk-gateway"
alterator_api_version=1

. alterator-sh-functions

asterisk_reload()
{
	/usr/sbin/asterisk -rx 'sip reload' 2>&1 > /dev/null
	/usr/sbin/asterisk -rx 'dialplan reload' 2>&1 > /dev/null
}

write_configs()
{
	if ! grep -q '#include "sip.gateway.conf"' /etc/asterisk/sip.conf; then
		echo -e '\n#include "sip.gateway.conf"\n' >> /etc/asterisk/sip.conf
	fi
	if ! grep -q '#include "extensions.gateway.conf"' /etc/asterisk/extensions.conf; then
		echo -e '\n#include "extensions.gateway.conf"\n' >> /etc/asterisk/extensions.conf
	fi
    GATEWAY_IP="$1"
cat > /etc/asterisk/sip.gateway.conf << __F1__
[$GATEWAY_IP]
type=friend
insecure=very
host=$GATEWAY_IP
context=from-gateway
disallow=all
allow=alaw
__F1__
cat > /etc/asterisk/extensions.gateway.conf << __F1__
[from-pstn]
exten => _X.,1,Dial(SIP/$GATEWAY_IP/\${EXTEN})

[from-gateway]
exten => _X.,1,Dial(DAHDI/g0/\${EXTEN})
__F1__
}

write_configs "$GATEWAY_IP"

on_message() {
  case "$in_action" in
    read)
	if [ -f /etc/asterisk/GATEWAY_IP ]; then
	    GATEWAY_IP=`cat /etc/asterisk/GATEWAY_IP`
	fi
	write_string_param ip "$GATEWAY_IP"
	;;
    write)
		echo "$in_ip" > /etc/asterisk/GATEWAY_IP
		write_configs "$in_ip"
		asterisk_reload
	;; #insert your code for write action here
    list)  ;; #insert your code for list action here
    type)
	write_type_item ip ipv4-address
	;;
  esac
}

message_loop

