#! /bin/sh
#
# /etc/init.d/nstxcd: start and stop the nstx IP over DNS client

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/nstxcd
NAME=nstxcd
DESC=nstxcd

test -x $DAEMON || exit 0

# Include nstx defaults if available
if [ -f /etc/default/nstx ] ; then
	. /etc/default/nstx
fi

set -e

check_start_nstxcd_option() {
    if [ ! "$start_nstxcd" = "yes" ]; then
	echo "Not starting nstx client, disabled via /etc/default/nstx"
	return 1
    else
	return 0
    fi
}


case "$1" in
  start)
  if check_start_nstxcd_option; then
	echo -n "Starting $DESC: "
	start-stop-daemon --start -b -m --quiet --pidfile /var/run/$NAME.pid \
		--exec $DAEMON -- $NSTX_DOMAIN $NSTX_DNS_SERVER
	sleep 1;
	if [ "$ifup_tun0" = "yes" ]; then
	    ifup tun0
	fi
	echo "$NAME."
  else
      RET=1
  fi
	;;
  stop)
	echo -n "Stopping $DESC: "
	if [ "$ifup_tun0" = "yes" ]; then
	    ifdown tun0
	fi
	start-stop-daemon --stop -m -o --quiet --pidfile /var/run/$NAME.pid \
		--exec $DAEMON
	echo "$NAME."
	;;
  restart|force-reload)
	#
	#	If the "reload" option is implemented, move the "force-reload"
	#	option to the "reload" entry above. If not, "force-reload" is
	#	just the same as "restart".
	#
	echo -n "Restarting $DESC: "
	if [ "$ifup_tun0" = "yes" ]; then
	    ifdown tun0
	fi
	start-stop-daemon --stop -m -o --quiet --pidfile \
		/var/run/$NAME.pid --exec $DAEMON
	sleep 1
	if check_start_nstxcd_option; then
	    start-stop-daemon --start -b -m --quiet --pidfile \
		/var/run/$NAME.pid --exec $DAEMON -- $NSTX_DOMAIN $NSTX_DNS_SERVER
	    sleep 1;
	    if [ "$ifup_tun0" = "yes" ]; then
		ifup tun0
	    fi
	    echo "$NAME."
	else
	    RET=1
	fi
	;;
  *)
	N=/etc/init.d/$NAME
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
