#!/bin/sh

# Bring up/down dynDNSd

. /etc/sysconfig/rc.conf
. /bin/network-functions

. /etc/image_features

SETSID=/usr/bin/setsid

#use dyndns.pl as client
USE_DYNDNS_PL=0

USE_DYNDNS_PL=1

PIDFILE=/var/run/ez-ipupdate.pid
SERVICE=dyndnsd
PROCESS_NAME=ez-ipupdate

if [ "$USE_DYNDNS_PL" = "1" ] ; then
	PROCESS_NAME=dyndns-daemon
	PIDFILE=/var/run/dyndns.pid
	if [ ! -d /var/log/dyndns ] ; then
		mkdir -p /var/log/dyndns
	fi
fi

# This script accepts two parameters in case of start

DYN_INTERFACE=$2
DYN_ADDRESS=$3

do_start ()
{
	if ! ServiceCheckRunning1 ; then
		return $?
	fi

	/etc/init.d/softdogd wait
	echo "<--erase fiadlog-->" > /tmp/logs/dyndns.log

	if [ -z "$DYN_INTERFACE" ] || [ -z "$DYN_ADDRESS" ] ; then
		if [ ! -f /var/run/interfaces ] ; then
			echo "You must specify DYN_INTERFACE and DYN_ADDRESS as parameters"
			exit 1
		fi

		. /var/run/interfaces

		DYN_INTERFACE="$VIRT_WAN"
		DYN_ADDRESS=`/bin/addr -i "$VIRT_WAN" -a`

		if [ -z "$DYN_ADDRESS" ] ; then
			echo "Interface not available"
			echo "Interface $VIRT_WAN is currently not available" > /tmp/logs/dyndns.log
			/bin/raise_event -a system -n DynDNS -t "Interface $VIRT_WAN is currently not available"
			exit 1
		fi
	fi

#if [ "$FEATURE_FIREWALL" = "1" ] ; then
#	/bin/firewall_blocking system add dyndns > /dev/null 2>&1
#fi

	if [ "$USE_DYNDNS_PL" = "1" ] ; then
		$SETSID /bin/$PROCESS_NAME --file-default --Config /etc/fiad-conf/dyndns.conf --ethernet $DYN_INTERFACE --debug 2
		
	else
		$SETSID /bin/$PROCESS_NAME --log-file /tmp/logs/dyndns.log --pid-file $PIDFILE --daemon --address $DYN_ADDRESS --interface $DYN_INTERFACE --config-file /etc/fiad-conf/ez.conf --debug > /dev/null 2>&1
	fi

	return $?
}

do_stop ()
{
	if ! ServiceStop ; then
		return $?
	fi
	/etc/init.d/softdogd wait

#if [ "$FEATURE_FIREWALL" = "1" ] ; then
#	/bin/firewall system del dyndns > /dev/null 2>&1
#fi
	return $?
}

do_status ()
{
	ServiceStatus

	return $?
}

case "$1" in
	start)
		do_start
		;;
	stop)
		do_stop
		;;
	status)
		do_status
		;;
	restart)
		do_stop
		do_start
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 1
esac

exit $?
