#!/bin/sh

nat_restart_check()
{
	local modules="all onenat napt vs pt dmz alg"
	local update_module=""

	{
		flock -x 50
		for module in ${modules}; do
			[ -e "/tmp/.nat/${module}_update" ] && [ "$(cat /tmp/.nat/${module}_update)" = "1" ] && {
				update_module="${module}"
				break
			}
		done

		flock -u 50
	} 50<>/tmp/nat.lock

	[ "${update_module}" != "" ] && {
		/etc/init.d/nat restart ${update_module}
		return 0
	}

	return 1
}


case "$1" in
	hotplug)
		if [ "$2" = "2" -a ! -f "/var/run/nat_bg.hotplug.miss" ];then
			exit 0
		else
			rm "/var/run/nat_bg.hotplug.miss"
		fi

		# we _do_ _not_ restart nat during iface events,so check onenat subinterfaces' status asynchronously
		[ -f "/tmp/.nat/one_nat_id" ] && {
			lock /var/.nat/one_nat_id.lock
			while read line; do $line; done < /tmp/.nat/one_nat_id
			lock -u /var/.nat/one_nat_id.lock
		}

		env -i CLEAN=on MODULE=NAPT /sbin/hotplug-call nat;;
	loop) while nat_restart_check;do :; done;;
esac
