#!/bin/sh
. /etc/iproute2/script/gateway-mgt-function

hostinfo="$1"
state="$2"
debug="$3"

. ${hostinfo}

PRIMARY_DNS="NULL"
DHCP_TABLE_ID="28998"

# Fix multi gateway bug, synonetd support only one gateway
GATEWAY="`echo ${GATEWAY} | cut -d',' -f1`"

# Workaround for support case: #1094841
# If get netmask 255.255.255.255, recalculate default netmask for ipaddr
if [ "x255.255.255.255" = "x${NETMASK}" ]; then
	IP_NETWORK=`ipcalc -n ${IPADDR} ${NETMASK}`
	GW_NETWORK=`ipcalc -n ${GATEWAY} ${NETMASK}`

	# Do check ipaddr and gateway are in the same subnet.
	# If not, set netmask to ip default netmask.
	if [ "x${IP_NETWORK}" != "x${GW_NETWORK}" ]; then
		NETMASK=`ipcalc -m ${IPADDR} | sed 's/NETMASK=//g'`
		/sbin/ifconfig ${INTERFACE} ${IPADDR} netmask ${NETMASK}
	fi
fi

if test -n "${DNS}" ; then
	local dns_array=`echo ${DNS} | sed "s/,/ /g"`
	for dns in ${dns_array}
	do
		PRIMARY_DNS="${dns}"
		break;
	done
fi

if [ "xdown" = "x${state}" ]; then
	/usr/syno/sbin/synonetdtool --del-gateway-info -4 ${INTERFACE}
	/usr/syno/sbin/synonetdtool --refresh-gateway -4
	exit 0
fi

/usr/syno/sbin/synonetdtool --add-gateway-info -4 -2 ${INTERFACE} ${GATEWAY} ${PRIMARY_DNS} ethernet

/usr/syno/sbin/synonetdtool --refresh-gateway -4

local enable_multi_gateway=`/bin/get_key_value /etc/synoinfo.conf multi_gateway`
if [ "xyes" = "x${enable_multi_gateway}" ]; then
	/usr/syno/sbin/synonetdtool --add-policy-route-rule -4 multi-gateway ${INTERFACE} NULL NULL ${GATEWAY}
	/usr/syno/sbin/synonetdtool --refresh-route-table -4 ${INTERFACE} ${IPADDR}
fi

if [ "x" != "x${CLASSLESS_STATICROUTE_NUMBER}" ]; then
	ip -4 rule del table ${DHCP_TABLE_ID}
	ip -4 rule add from all lookup "${DHCP_TABLE_ID}" priority "${DHCP_TABLE_ID}"

	for i in $(seq 1 ${CLASSLESS_STATICROUTE_NUMBER});
	do
		eval ROUTE="\$CLASSLESS_STATICROUTE_$i"
		DST=$(echo "${ROUTE}" | cut -d, -f1)
		VIA=$(echo "${ROUTE}" | cut -d, -f2)
		ip -4 route add "${DST}" via "${VIA}" dev "${INTERFACE}" table "${DHCP_TABLE_ID}"
	done
fi

# refresh static routing rules when an IP address is obtained via DHCP
/usr/syno/sbin/synonetdtool --refresh-static-route-rules

# 6rd
if [ "x" != "x${SixrdIpv4Mask}" ]; then
/usr/syno/sbin/synonetdtool --load-6rd-info ${INTERFACE} ${SixrdIpv4Mask} ${SixrdPrefix}/${SixrdPrefixLength} ${BorderRelayIp}
fi

