# vim: set ft=sh noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 :

_setup_route() {
	if ip route "$1" "$2" via "$3" dev "$4" metric "$5" 2>/dev/null; then
		_log "$1 $2 route for $4 using gateway $3 and metric $5"
	fi
}

_setup_route6() {
	if ip -6 route "$1" "$2" via "$3" dev "$4" metric "$5" 2>/dev/null; then
		_log "$1 $2 ipv6 route for $4 using gateway $3 and metric $5"
	fi
}

_setup_high_priority_rule() {
	mark="0x7874756e"
	# We can't select the route using ip rule list with our version of ip route
	matching_rules=$(ip rule list | grep -c "fwmark $mark")
	[ "$matching_rules" -gt 0 ] && [ "$1" = "add" ] && return
	[ "$matching_rules" = 0 ] && [ "$1" = "del" ] && return

	# pref 30000 to be between the interfaces rules (20000, value set by
	# netifd) and the main routing table (32766, default value)
	_log "$1 rule matching $mark using table $2 and pref 30000"
	ip rule "$1" fwmark "$mark" table "$2" pref 30000
}

config_load glorytun
otb_host= ; config_get otb_host tun0 server

config_load network
otb_metric= ; config_get otb_metric "$OTB_TRACKER_INTERFACE" metric

[ "$OTB_TRACKER_STATUS" = "OK" ] && action="add" || action="del"

if [ "$OTB_TRACKER_INTERFACE" = "tun0" ] ;then
	# Don't add a static route to the otb host
	otb_host=
	# Default route
	otb_metric=0
	otb_metric_6=1
fi

# Add IPv4 default route
_setup_route "$action" default "$OTB_TRACKER_DEVICE_GATEWAY" "$OTB_TRACKER_DEVICE" "$otb_metric"
[ -n "$otb_host" ] && _setup_route \
	"$action" \
	"$otb_host" \
	"$OTB_TRACKER_DEVICE_GATEWAY" \
	"$OTB_TRACKER_DEVICE" \
	"$otb_metric"

# Add IPv6 default route
[ -n "$OTB_TRACKER_DEVICE_GATEWAY_V6" ] && {
	_setup_route6 "$action" default "$OTB_TRACKER_DEVICE_GATEWAY_V6" "$OTB_TRACKER_DEVICE" "$otb_metric_6"
}

dns_servers=$(ubus call "network.interface.$OTB_TRACKER_INTERFACE" status | \
	jq -r '."dns-server" // [] | join(" ")')

[ -n "$dns_servers" ] && for dns_server in $dns_servers; do
	 _setup_route \
		"$action" \
		"$dns_server" \
		"$OTB_TRACKER_DEVICE_GATEWAY" \
		"$OTB_TRACKER_DEVICE" \
		"$otb_metric"
done
