#!/bin/sh
. /etc/functions.sh
PPP_IFACE="$1"
PPP_TTY="$2"
PPP_SPEED="$3"
PPP_LOCAL="$4"
PPP_REMOTE="$5"
PPP_IPPARAM="$6"

unit="${PPP_IFACE##ppp}"
if [ "$unit" -ge "30" ]; then
	if [ "$unit" -le "400" ]; then
		ddev=$(route | grep default | awk '{printf $8}')
		[ "$ddev" == "$PPP_IFACE" ] && {
			route del default
			restore_default_route
			flush-ipconntrack 1 &
		}
		idx=0
		while [ $(uci -q -c /etc/config/grocx/ get pptp.$idx.ppp_num) != "$unit" -a "$idx" -lt "32" ]; do
			idx="$(($idx + 1))"
		done
		if [ "$idx" -lt "32" ]; then
			Tname=$(uci -q -c /etc/config/grocx/ get pptp.$idx.name)
			/sbin/pptp_static_route del T$Tname $PPP_IFACE
		fi
		
		# remove rule for nat mode
		iptables -t nat -D POSTROUTING -s $(uci -q get network.lan.ipaddr)/$(uci -q get network.lan.netmask) -o $PPP_IFACE -j MASQUERADE 2>/dev/null
	fi
	rnet=$(uci -q -P /var/state get network.vpnup.rnet_$PPP_IFACE)
	rmask=$(uci -q -P /var/state get network.vpnup.rmask_$PPP_IFACE)
	wan_dev=$(uci -p /var/state/ -q get network.wan.ifname)
	iptables -t nat -D zone_wan_nat -s $rnet/$rmask -o $wan_dev -j MASQUERADE > /dev/null 2>&1
	uci -q -P /var/state revert network.vpnup.$PPP_IFACE		
	uci -q -P /var/state revert network.vpnup.mppe_$PPP_IFACE
	uci -q -P /var/state revert network.vpnup.rnet_$PPP_IFACE
	uci -q -P /var/state revert network.vpnup.rmask_$PPP_IFACE
fi

ipdown=$(cat /proc/uptime | awk 'FS="[.]+" {print $1}')
export PPP_IFACE PPP_TTY PPP_SPEED PPP_LOCAL PPP_REMOTE PPP_IPPARAM
[ -z "$PPP_IPPARAM" ] || {

	if [ "$PPP_IPPARAM" == "wan" ]; then
		# remove the interface's network state (only when it was not removed in ifdown)
		uptime=$(uci -q -P /var/state get network.wan.uptime | awk 'FS="[.]+" {print $1}')
		if [ -n "$uptime" -a $ipdown -ge $uptime ]; then
			logger "revert uci network state in ip-down..."
			uci_revert_state network "$PPP_IPPARAM"
		fi
	else
		# remove the interface's network state
		uci_revert_state network "$PPP_IPPARAM"
	fi

	env -i ACTION="ifdown" INTERFACE="$PPP_IPPARAM" DEVICE="$PPP_IFACE" PROTO=ppp /sbin/hotplug-call "iface"
}

[ -d /etc/ppp/ip-down.d ] && {
	for SCRIPT in /etc/ppp/ip-down.d/*
	do
		[ -x "$SCRIPT" ] && "$SCRIPT" $@
	done
}
