#!/bin/sh

### BEGIN INIT INFO
# Provides:		miniupnpd
# Required-Start:	$remote_fs
# Required-Stop:	$remote_fs
# Should-Start:		$local_fs $network $time
# Should-Stop:		$local_fs $network $time
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	Lightweight UPnP IGD & PCP/NAT-PMP daemon
# Description:		MiniUPnPd is a small daemon which can be installed on a
#			NAT router to provide UPnP IGD & PCP/NAT-PMP port
#			mapping services, enabling clients on the LAN to ask for
#			port maps. It is compatible with peer-to-peer software,
#			messaging applications, and games consoles that connect
#			to online services (including Xbox LIVE and the
#			PlayStation Network).
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DAEMON_NAME="MiniUPnPd"
DAEMON_SERVICE_NAME="Lightweight UPnP IGD & PCP/NAT-PMP daemon"
DAEMON=/usr/sbin/miniupnpd
PIDFILE=/var/run/miniupnpd.pid
CONFFILE=/etc/miniupnpd/miniupnpd.conf
DEFAULT=/etc/default/miniupnpd
SCRIPT_DIR=/etc/miniupnpd

. /lib/lsb/init-functions

if [ -r /lib/init/vars.sh ] ; then
	. /lib/init/vars.sh
fi

read_config () {
	sed -rn '
s|^\s*'"${2}"'='\''([^'\'']+)'\''\s*$|\1|g
t hold
s|^\s*'"${2}"'='\"'([^'\"']+)'\"'\s*$|\1|g
t hold
s|^\s*'"${2}"'=(\S+)\s*$|\1|
t hold
b
: hold
p
	' "${1}"
}

# Make sure the package hasn't been removed but not purged
if ! [ -x ${DAEMON} ] ; then
	exit 0
fi

case "${1}" in
	start)
		if [ "${START_DAEMON}" = 0 ] ; then
			log_daemon_msg "${DAEMON_NAME}: ${DEFAULT} isn't set to START_DAEMON=1: exiting"
			log_end_msg 1

			exit 0
		fi

		log_daemon_msg "Initializing ${DAEMON_SERVICE_NAME} *tables" "${DAEMON_NAME}"
		if ! /usr/libexec/miniupnpd-startstop-helper.sh start ; then
			log_end_msg 1
			exit 2
		fi

		start-stop-daemon -q --start --exec "${DAEMON}" -- ${MiniUPnPd_OTHER_OPTIONS}
		RET="${?}"

		case "${RET}" in
			0|1)
				log_end_msg 0
				;;

			*)
				log_end_msg 1

				exit 1
				;;
		esac
		;;

	stop)
		log_daemon_msg "Stopping ${DAEMON_SERVICE_NAME}" "${DAEMON_NAME}"

		start-stop-daemon -q --stop --oknodo --pidfile ${PIDFILE}
		RET="${?}"

		log_daemon_msg "Deconfiguring ${DAEMON_SERVICE_NAME} *tables" "${DAEMON_NAME}"
		/usr/libexec/miniupnpd-startstop-helper.sh stop

		case "${RET}" in
			0|1)
				log_end_msg 0
				;;

			*)
				log_end_msg 1

				exit 1
				;;
		esac
		;;

	restart|force-reload)
		${0} stop
		case "$?" in
			0|1)
				${0} start
				case "$?" in
					0) log_end_msg 0 ;;
					1) log_end_msg 1 ;; # Old process is still running
					*) log_end_msg 1 ;; # Failed to start
				esac
				;;
			*)
				# Failed to stop
				log_end_msg 1
				;;
		esac
		;;

	status)
		status_of_proc "${DAEMON}" "${DAEMON_NAME}"
		exit ${?}
		;;

	*)
		echo "Usage: ${0} {start|stop|restart|status}"
		exit 1
		;;
esac

exit 0
