#!/bin/sh

CONF_PATH=/etc/telephony
APP_PATH=/bin
AUTO_PROVISION_CLIENT=autoprovisionclient

# start Auto Provision Client
do_start ()
{
	/etc/init.d/softdogd wait
	/bin/setsid $APP_PATH/$AUTO_PROVISION_CLIENT $CONF_PATH > /dev/null 2>&1 &
	
	return 0
}

# stop Auto Provision Client
do_stop ()
{
	/etc/init.d/softdogd wait
	
	/bin/killall $AUTO_PROVISION_CLIENT > /dev/null 2>&1
	
	return 0
}

# Check status
do_status ()
{
	/bin/killall -0 $AUTO_PROVISION_CLIENT > /dev/null 2>&1
	if [ $? != 0 ] ; then
		echo "$AUTO_PROVISION_CLIENT is in an undefined state or is not running."
		return 2
	fi

	echo "$AUTO_PROVISION_CLIENT is up and running."
	return 0
}


case "$1" in
	start)
		ISSTANDALONEMODE=$(cat /mnt/flashfs/configs/current/telephony/default/servicesdb | grep "mailbox_service=0")
		if [ "$ISSTANDALONEMODE" != "" ] ; then
			# Enable mailing service
			cp -f /mnt/flashfs/configs/current/telephony/default/servicesdb /tmp/servicesdb1
			/bin/sed s/mailbox_service=0/mailbox_service=2/g /tmp/servicesdb1 > /tmp/servicesdb2
			cp -f /tmp/servicesdb2 /mnt/flashfs/configs/current/telephony/default/servicesdb
			rm -f /tmp/servicesdb1 /tmp/servicesdb2
			/etc/init.d/voice restart
		fi
		do_start
		;;
	stop)
		do_stop
		ISSTANDALONEMODE=$(cat /mnt/flashfs/configs/current/telephony/default/servicesdb | grep "mailbox_service=0")
		if [ "$ISSTANDALONEMODE" = "" ] ; then
			# Disable mailing service
			cp -f /mnt/flashfs/configs/current/telephony/default/servicesdb /tmp/servicesdb1
			/bin/sed s/mailbox_service=2/mailbox_service=0/g /tmp/servicesdb1 > /tmp/servicesdb2
			cp -f /tmp/servicesdb2 /mnt/flashfs/configs/current/telephony/default/servicesdb
			rm -f /tmp/servicesdb1 /tmp/servicesdb2
			/etc/init.d/voice restart
		fi
		;;
	status) 
		do_status
		;;
	restart)
		do_stop
		ISSTANDALONEMODE=$(cat /mnt/flashfs/configs/current/telephony/default/servicesdb | grep "mailbox_service=0")
		if [ "$ISSTANDALONEMODE" != "" ] ; then
			# Enable mailing service
			cp -f /mnt/flashfs/configs/current/telephony/default/servicesdb /tmp/servicesdb1
			/bin/sed s/mailbox_service=0/mailbox_service=2/g /tmp/servicesdb1 > /tmp/servicesdb2
			cp -f /tmp/servicesdb2 /mnt/flashfs/configs/current/telephony/default/servicesdb
			rm -f /tmp/servicesdb1 /tmp/servicesdb2
			/etc/init.d/voice restart
		fi
		/bin/sleep 3
		do_start
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 1
esac

exit $?
