#!/bin/sh
# After a hard power-cut, continuous LAN traffic can create conntrack
# entries before MASQUERADE is ready. Those flows stay non-NATed forever
# (new pings get NAT; the old ping keeps 192.168.1.x as source).
# Reload firewall and flush conntrack once wwan/wlan0 is up.

[ "$ACTION" = ifup -o "$ACTION" = ifupdate -o "$ACTION" = connected ] || exit 0

need_reload=0
[ "$INTERFACE" = wwan ] && need_reload=1
[ "$INTERFACE" = wwan_4 ] && need_reload=1
[ "$DEVICE" = wlan0 ] && need_reload=1
[ "$need_reload" = 1 ] || exit 0

/etc/init.d/firewall enabled || exit 0

(
	sleep 3
	[ -x /sbin/fw3 ] && fw3 -q reload
	if [ -d /sys/class/net/wlan0 ]; then
		iptables -t nat -C POSTROUTING -o wlan0 -j MASQUERADE 2>/dev/null || \
			iptables -t nat -I POSTROUTING -o wlan0 -j MASQUERADE
	fi
	# Drop stale LAN->WAN flows so they recreate with SNAT applied.
	if [ -x /usr/sbin/conntrack ]; then
		conntrack -F
	elif [ -e /proc/net/nf_conntrack ]; then
		echo f > /proc/net/nf_conntrack
	fi
	logger -t ltrx-nat "Reloaded NAT/conntrack after $ACTION $INTERFACE ($DEVICE)"
) &
