#!/bin/sh

local IGMP_WAN=$(uci -q get igmp.global.pxy_wan)
local IGMP_WAN_PROTO=$(uci -q get network.$IGMP_WAN.proto)
local IGMP_IFNAME=""

if [ "$IGMP_WAN_PROTO" == "pppoe" ]; then
	ppp=$(uci -q get network.$IGMP_WAN.unit)
	IGMP_IFNAME="ppp$ppp"
else
	IGMP_IFNAME=$(uci -q get network.$IGMP_WAN.ifname)
fi

start_igmpproxy() {
	/usr/sbin/igmpproxy /etc/igmpproxy.conf &
	iptables -t nat -A POSTROUTING -o $IGMP_IFNAME -j MASQUERADE > /dev/null 2>&1
}

stop_igmpproxy() {
	iptables -t nat -D POSTROUTING -o $IGMP_IFNAME -j MASQUERADE > /dev/null 2>&1
	killall igmpproxy
}

if [ $1 == "start" ]; then
	start_igmpproxy
fi

if [ $1 == "stop" ]; then
	stop_igmpproxy
fi

if [ $1 == "restart" ]; then
	stop_igmpproxy
	sleep 1
	start_igmpproxy
fi

if [ $1 == "check" ]; then
	stop_igmpproxy
	local igmp=$(uci -q get igmp.global.pxy_enable 2>/dev/null)
	if [ "$igmp" = "1" ] ; then
		start_igmpproxy
	fi
fi