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

START=19
STOP=19

get_hnat_status(){
	status=0
	hwnat_en=0

	config_load hwnat

	config_get_bool hwnat_en global enabled
	if [ "$hwnat_en" == "0" ] ; then
		echo $status
		return
	fi

	hnat_sens_table=`uci -c /etc/profile.d show profile.@hwnat[0] | sed '1d' | cut -d "." -f 3 | cut -d "=" -f 1 `
	if [ -n "$hnat_sens_table" ]; then
		for sens_module in ${hnat_sens_table}
		do
			config_get_bool module_stat module ${sens_module}
			if [ "$module_stat" == "1" ] ; then
				echo $status
				return
			fi
		done
	fi

	status=1
	echo $status
}

get_current_hnat_status(){
	status=0

	[ ! -d /sys/kernel/debug/hnat ] && /bin/mount -o noatime -t debugfs debugfs /sys/kernel/debug
	status_value=`cat /sys/kernel/debug/hnat/hook_toggle`

	if [ "$status_value" == "1" ] ; then
		status=1
	fi
	echo $status
}

start() {
	local version=`uname -r`
	local hwnat_en
	config_load hwnat

	config_get_bool hwnat_en global enabled
	if [ "$hwnat_en" = "1" ]; then
		if [ -d /sys/module/mtkhnat ]; then
			echo 1 > /sys/kernel/debug/hnat/hook_toggle
		else
			insmod /lib/modules/$version/mtkhnat.ko
			echo "1 5" > /sys/kernel/debug/hnat/hnat_setting
		fi
	fi
	echo 1 > /tmp/hnat_start_complete
}

stop() {
	[ -d /sys/module/mtkhnat ] && echo 0 > /sys/kernel/debug/hnat/hook_toggle
}

reload() {
	if [ -f /tmp/hnat_start_complete ] ; then
		current_hnat_status=`get_current_hnat_status`
		expect_hnat_status=`get_hnat_status`
		if [[ "$current_hnat_status" == "1" && "$expect_hnat_status" == "0" ]] ; then
			stop
		elif [[ "$current_hnat_status" == "0" && "$expect_hnat_status" == "1" ]] ; then
			start
		fi
	fi
}
