#! /bin/sh

. /etc/init.d/functions.sh
. /etc/conf.d/libupnp

PARHAND_UPNP_CONF=/usr/etc/param/par_network_upnp.conf

. /etc/conf.d/net.eth0
[ -e $RCLIB/sh/rc-dhcp.sh ] && . $RCLIB/sh/rc-dhcp.sh

scope_name2id() {
	local _id

	_id=$(sed -rne \
		"s/[[:space:]]*([0-9]+)[[:space:]]+$1[[:space:]]*/\1/p" \
		/etc/iproute2/rt_scopes)
	if [ "$_id" ]; then
		echo "$_id"
	else
		echo $1
	fi
}

# Lock file
_lockf="upnp_friendlyname"

unlock() {
	remove_lock_file "$_lockf"
}

lock() {
	trap unlock EXIT QUIT INT TERM
	create_lock_file "$_lockf"
}

default_friendlyname() {
	local friendlyname

	lock


	if [ -z "$UPNP_FRIENDLYNAME" ]; then
		friendlyname=$(default_friendlyname.sh)

		# Replace (or add) UPNP_FRIENDLYNAME.
		sed -i -e '/^[[:space:]]*UPNP_FRIENDLYNAME=.*$/d' \
			/etc/conf.d/libupnp
		echo "UPNP_FRIENDLYNAME='$friendlyname'" \
			>> /etc/conf.d/libupnp


		# Make parhand aware of the change.
		parhandclient readgroupfile $PARHAND_UPNP_CONF
	fi

	unlock
}

start_libupnp() {
	default_friendlyname || return 1

	[ -e $LIBUPNP_RUNDIR ] || mkdir $LIBUPNP_RUNDIR || return 1

	if [ "$UPNP_ENABLED" = yes ] && [ "$INET_ENABLED" != no ]; then
		# Get IP address with lowest scope ID.
		IPADDR=$(ip -f inet address show dev eth0 | {
			local _line _minscope _addr _scope
			read _line
			_minscope=256 # Initialize to max+1
			while read _line; do
				_addr="${_line#inet }"
				_addr="${_addr%% *}"
				_scope="${_line##* scope }"
				_scope=$(scope_name2id ${_scope%% *})
				if [ $_scope -lt $_minscope ]; then
					IPADDR="${_addr%%/*}"
					_minscope=$_scope
				fi
			done
			echo $IPADDR
			})

		[ "$IPADDR" ] && LIBUPNP_OPTIONS="-i $IPADDR $LIBUPNP_OPTIONS"

		# Get router
		ROUTER=$(ip -f inet route list 0.0.0.0/0 | \
			sed -rne 's/^default via ([0-9.]+).*/\1/p')
		[ "$ROUTER" ] && LIBUPNP_OPTIONS="-r $ROUTER $LIBUPNP_OPTIONS"

		start_daemon -c upnp -g upnp /bin/libupnp $LIBUPNP_OPTIONS
		echo "$UPNP_INTERFACE" > $LIBUPNP_RUNDIR/libupnp.state
	else
		information "disabled"
	fi
}

stop_libupnp() {
	stop_daemon /bin/libupnp
}

case "$1" in
	start)
		begin "Starting libupnp"
		start_libupnp
		end $?
		;;
	stop)
		begin "Stopping libupnp"
		stop_libupnp
		end $?
		;;
	restart)
		begin "Restarting libupnp"
		stop_libupnp && start_libupnp
		end $?
		;;
	*)
		error "Usage: $0 start|stop|restart"
		;;
esac

exit 0
