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

. "${IPKG_INSTROOT}/lib/mwan3/common.sh"
. "${IPKG_INSTROOT}/lib/functions/network.sh"
. "${IPKG_INSTROOT}/lib/mwan3/mwan3.sh"

START=19
USE_PROCD=1
SCRIPTNAME="mwan3-init"

service_running() {
	[ -d "$MWAN3_STATUS_DIR" ]
}

start_tracker() {
	local enabled interface
	interface=$1
	config_get_bool enabled $interface 'enabled' '0'
	[ $enabled -eq 0 ] && return
	[ -z "$(config_get $interface track_ip)" ] && return

	procd_open_instance "track_${1}"
	procd_set_param command /usr/sbin/mwan3track $interface
	procd_set_param respawn
	procd_close_instance
}

start_service() {
	local enabled hotplug_pids

	mwan3_init
	config_foreach start_tracker interface

	mwan3_update_iface_to_table
	mwan3_set_connected_ipset
	mwan3_set_custom_ipset
	mwan3_set_general_rules
	mwan3_set_general_iptables
	config_foreach mwan3_ifup interface "init"
	wait $hotplug_pids
	mwan3_set_policies_iptables
	mwan3_set_user_rules

	procd_open_instance rtmon_ipv4
	procd_set_param command /usr/sbin/mwan3rtmon ipv4
	procd_set_param respawn
	procd_close_instance

	if command -v ip6tables > /dev/null; then
		procd_open_instance rtmon_ipv6
		procd_set_param command /usr/sbin/mwan3rtmon ipv6
		procd_set_param respawn
		procd_close_instance
	fi
}

stop_service() {
	local ipset rule IP IPTR IPT family table tid

	mwan3_init
	config_foreach mwan3_interface_shutdown interface

	for family in ipv4 ipv6; do
		if [ "$family" = "ipv4" ]; then
			IPT="$IPT4"
			IPTR="$IPT4R"
			IP="$IP4"
		elif [ "$family" = "ipv6" ]; then
			[ $NO_IPV6 -ne 0 ] && continue
			IPT="$IPT6"
			IPTR="$IPT6R"
			IP="$IP6"
		fi

		for tid in $($IP route list table all | sed -ne 's/.*table \([0-9]\+\).*/\1/p' | sort -u); do
			[ $tid -gt $MWAN3_INTERFACE_MAX ] && continue
			$IP route flush table $tid &> /dev/null
		done

		for rule in $($IP rule list | grep -E '^[1-3][0-9]{3}\:' | cut -d ':' -f 1); do
			$IP rule del pref $rule &> /dev/null
		done
		table="$($IPT -S)"
		{
			echo "*mangle";
			[ -z "${table##*PREROUTING -j mwan3_hook*}" ] && echo "-D PREROUTING -j mwan3_hook"
			[ -z "${table##*OUTPUT -j mwan3_hook*}" ] && echo "-D OUTPUT -j mwan3_hook"
			echo "$table" | awk '{print "-F "$2}' | grep mwan3 | sort -u
			echo "$table" | awk '{print "-X "$2}' | grep mwan3 | sort -u
			echo "COMMIT"
		} | $IPTR
	done

	for ipset in $($IPS -n list | grep mwan3_); do
		$IPS -q destroy $ipset
	done

	for ipset in $($IPS -n list | grep mwan3 | grep -E '_v4|_v6'); do
		$IPS -q destroy $ipset
	done

	rm -rf $MWAN3_STATUS_DIR $MWAN3TRACK_STATUS_DIR

}

reload_service() {
	stop
	start
}

service_triggers() {
	procd_add_reload_trigger 'mwan3'
}
