#!/bin/sh /etc/rc.common

START=96

boot()
{
	state=`uci get upnp.default.state 2>/dev/null`

	if [ "$state" == "on" ];then
		ret=$(iptables -t mangle -nL PREROUTING -w|grep "239.255.255.250")
		[ -z "$ret" ] && iptables -w -t mangle -I PREROUTING -p udp -d 239.255.255.250 --dport 1900 -j ACCEPT 
		vnete /usr/sbin/upnpd &
	fi
}

start()
{	
	ret=`ps |grep upnpd |grep -v "grep"`
	if [ -n "$ret" ]; then
		pid=`echo $ret | cut -d " " -f 1`
		kill $pid &> /dev/null
	fi

	state=`uci get upnp.default.state 2>/dev/null`

	. /lib/upnp/upnp_api.sh

	if [ "$state" == "on" ];then
		ret=$(iptables -t mangle -nL PREROUTING -w|grep "239.255.255.250")
		[ -z "$ret" ] && iptables -w -t mangle -I PREROUTING -p udp -d 239.255.255.250 --dport 1900 -j ACCEPT 
		get_wan_ip_for_ipset
		install_lan_network_iptables_rules vnete
		edit_upnp_mdb add
		vnete /usr/sbin/upnpd &
	fi
}

stop()
{
	ret=`ubus list | grep "upnp"`
	if [ -n "$ret" ]; then   
			ubus call upnp upnp_stop
	fi
	. /lib/upnp/upnp_api.sh
	delete_all_nat_index
	sleep 2

	ret=`ps |grep upnpd |grep -v "grep"`
	if [ -n "$ret" ]; then
		pid=`echo $ret | cut -d " " -f 1`
		kill $pid &> /dev/null
	fi
	edit_upnp_mdb del
	iptables -t mangle -w -D PREROUTING -p udp -d 239.255.255.250 --dport 1900 -j ACCEPT 
	clean_iptables_rule
	clean_lan_network_iptables_rules vnete
}

restart() {
	stop
	start
}
