#!/bin/sh

. /lib/functions.sh
. /lib/mwan3/mwan3.sh
. /lib/functions/network.sh

[ "$ACTION" = "ifup" -o "$ACTION" = "ifdown" ] || exit 1
[ -n "$INTERFACE" ] || exit 2

if [ "$ACTION" = "ifup" ]; then
	[ -n "$DEVICE" ] || exit 3
fi

config_load mwan3
config_get_bool enabled globals 'enabled' '0'
[ ${enabled} -gt 0 ] || exit 0

config_get local_source globals local_source 'none'
[ "${local_source}" = "none" ] && {
	exit 0
}

[ "${local_source}" = "$INTERFACE" ] || {
	exit 0
}

mwan3_lock
src_ip=$(uci_get_state mwan3 globals src_ip)
[ "${src_ip}" != "" ] && {
	ip route del default via "${src_ip}" dev lo 1>/dev/null 2>&1
	ip addr del "${src_ip}/32" dev lo 1>/dev/null 2>&1
}

sleep 1

[ "$ACTION" = "ifup" ] && {
	network_get_ipaddr src_ip "${local_source}"
	if [ "${src_ip}" = "" ]; then
		$LOG warn "Unable to set source ip for own initiated traffic (${local_source})"
	else
		ip addr add "${src_ip}/32" dev lo
		ip route add default via "${src_ip}" dev lo
		uci_toggle_state mwan3 globals src_ip "${src_ip}"
	fi
}
mwan3_unlock

exit 0
