#! /bin/sh

### BEGIN INIT INFO
# Provides:          upnpd
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Linux UPnP Internet Gateway Device
# Description:       This is a daemon that emulates Microsoft's Internet
#                    Connection Service (ICS).  It implements the UPnP Internet
#                    Gateway Device specification (IGD) and allows UPnP aware
#                    clients, such as MSN Messenger to work properly from
#                    behind a NAT firewall.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/upnpd
NAME=upnpd
DESC="Linux IGD Daemon"

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

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

# Verify options
if [ -z "$EXT_IFACE" ] ; then
	log_warning_msg "External interface not specified in /etc/default/upnpd"
	exit 0
fi
if [ -z "$INT_IFACE" ] ; then
	log_warning_msg "Internal interface not specified in /etc/default/upnpd" >&2
	exit 0
fi

set -e

case "$1" in
  start)
	log_daemon_msg "Starting $DESC" "$NAME"
	route add -net 239.0.0.0 netmask 255.0.0.0 $INT_IFACE > /dev/null 2>&1 || true
	start-stop-daemon --start --quiet \
		--exec $DAEMON -- "$EXT_IFACE" "$INT_IFACE"
	log_end_msg $?
	;;
  stop)
	log_daemon_msg "Stopping $DESC" "$NAME"
	start-stop-daemon --stop --quiet \
		--exec $DAEMON
	route del -net 239.0.0.0 netmask 255.0.0.0 $INT_IFACE > /dev/null 2>&1 || true
	log_end_msg $?
	;;
  reset)
	log_daemon_msg "Resetting $DESC port mappings" "$NAME"
	start-stop-daemon --stop --signal USR1 --quiet \
		--exec $DAEMON
	log_end_msg $?
	;;
  restart|force-reload)
	log_daemon_msg "Restarting $DESC" "$NAME"
	start-stop-daemon --stop --quiet \
		--exec $DAEMON
	route del -net 239.0.0.0 netmask 255.0.0.0 $INT_IFACE > /dev/null 2>&1 || true
	sleep 1
	route add -net 239.0.0.0 netmask 255.0.0.0 $INT_IFACE > /dev/null 2>&1 || true
	start-stop-daemon --start --quiet \
		--exec $DAEMON -- "$EXT_IFACE" "$INT_IFACE" 
	log_end_msg $?
	;;
  status)
	echo -n "Status of $DESC: "
	if ps -C "$NAME" > /dev/null 2>&1; then
		echo "$NAME is running."
		exit 0
	else
		echo "$NAME is not running."
		exit 3
	fi
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|reset|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
