#!/bin/sh

SZD_SMARTWAN="/usr/syno/etc/smartwan/"
SZF_SMARTWAN_CONF=$SZD_SMARTWAN"smartwan.conf"
SZF_SERVICEORDER_CONF=$SZD_SMARTWAN"swlist_v4.conf"
SZF_RT_TABLES="/etc/iproute2/rt_tables"
SZF_GATEWAY_TABLES="/etc/iproute2/config/gateway_v4_priority"
SZF_SYNONETDTOOL="/usr/syno/sbin/synonetdtool"

# will be overwrite by lb_vars_set()
IF_GW1=ppp0
IF_GW2=eth0.1
GW1=168.95.98.254
GW2=10.11.71.254
NET_GW1=1.171.118.161
NET_GW2=10.11.68.0/22
IF_IP1=10.11.71.27
IF_IP2=36.227.42.238
WEIGHT1=50
WEIGHT2=50

lb_vars_set()
{
	local tmp=''

	# wan
	local display_ifname_1=`synogetkeyvalue ${SZF_SMARTWAN_CONF} smartwan_ifname_1`
	local display_ifname_2=`synogetkeyvalue ${SZF_SMARTWAN_CONF} smartwan_ifname_2`

	# eth0
	IF_GW1=`grep -A1 "\b${display_ifname_1}$" ${SZF_SERVICEORDER_CONF} | grep ifname | cut -d"=" -f2`
	IF_GW2=`grep -A1 "\b${display_ifname_2}$" ${SZF_SERVICEORDER_CONF} | grep ifname | cut -d"=" -f2`

	# check if interface and route really exist?
	ip addr show dev $IF_GW1 &> /dev/null
	if [ 0 -ne $? ]; then
		return
	fi
	ip addr show dev $IF_GW2 &> /dev/null
	if [ 0 -ne $? ]; then
		return
	fi

	# 10.11.71.254
	GW1=`cat ${SZF_GATEWAY_TABLES} | grep -A2 "\b${IF_GW1}$" | grep gateway | cut -d"=" -f2`
	GW2=`cat ${SZF_GATEWAY_TABLES} | grep -A2 "\b${IF_GW2}$" | grep gateway | cut -d"=" -f2`

	# 10.11.71.27
	# used for conntrack flush
	IF_IP1=`ip addr show dev $IF_GW1 | awk '$1=="inet"{print gensub("/.*","","",$2)}'`
	IF_IP2=`ip addr show dev $IF_GW2 | awk '$1=="inet"{print gensub("/.*","","",$2)}'`

	# 10.11.68.0/22
	# ip addr only gives 10.11.70.58/22, need to switch to 10.11.68.0/22
	# also ip addr dont give mask if it is 32, need to switch to xxx/32
	tmp="$IF_IP1 `/sbin/ifconfig $IF_GW1 | grep Mask | cut -d":" -f4`"
	eval $(/bin/ipcalc -np $tmp)
	NET_GW1="$NETWORK/$PREFIX"
	tmp="$IF_IP2 `/sbin/ifconfig $IF_GW2 | grep Mask | cut -d":" -f4`"
	eval $(/bin/ipcalc -np $tmp)
	NET_GW2="$NETWORK/$PREFIX"

	WEIGHT1=`synogetkeyvalue ${SZF_SMARTWAN_CONF} dw_weight_ratio`
	WEIGHT2=`echo "$((100-$WEIGHT1))"`
}

lb_vars_print()
{
	echo "interface 1: $IF_GW1, $IF_IP1, $GW1, $NET_GW1, $WEIGHT1"
	echo "interface 2: $IF_GW2, $IF_IP2, $GW2, $NET_GW2, $WEIGHT2"
}

##### 0. Preparation
lb_env_enable() {
	# this will not call dbus client, so it wont block synonetd
	$SZF_SYNONETDTOOL --enable-lb-route-table
}

##### 1. Routing rules (RPDB and FIB)
lb_route_rule_enable() {
	ip route add default via ${GW1} dev ${IF_GW1} table link1-table
	ip route add ${NET_GW1} dev ${IF_GW1} table link1-table
	ip route add default via ${GW2} dev ${IF_GW2} table link2-table
	ip route add ${NET_GW2} dev ${IF_GW2} table link2-table

	ip route add default proto static scope global table lb-table \
		nexthop via ${GW1} dev ${IF_GW1} weight ${WEIGHT1} \
		nexthop via ${GW2} dev ${IF_GW2} weight ${WEIGHT2}

	ip rule add prio 203 table main
	ip rule add prio 204 from ${NET_GW1} table link1-table
	ip rule add prio 205 from ${NET_GW2} table link2-table
	ip rule add prio 206 fwmark 0x40000/0x40000 table link1-table
	ip rule add prio 207 fwmark 0x80000/0x80000 table link2-table
	ip rule add prio 208 table lb-table

	ip route del default
}

##### 2. Firewall rules (using ipset to force a "flow" LB mode)
lb_firewall_rules_enable() {
	ipset create lb_link1 hash:ip,port,ip timeout 1200
	ipset create lb_link2 hash:ip,port,ip timeout 1200

	# Set firewall marks and ipset hash
	iptables -t mangle -A LB_SETMARK -o ${IF_GW1} -j MARK --set-mark 0x40000/0x40000
	iptables -t mangle -A LB_SETMARK -m mark --mark 0x40000/0x40000 -m set ! --match-set lb_link1 src,dstport,dst -j SET --add-set lb_link1 src,dstport,dst
	iptables -t mangle -A LB_SETMARK -o ${IF_GW2} -j MARK --set-mark 0x80000/0x80000
	iptables -t mangle -A LB_SETMARK -m mark --mark 0x80000/0x80000 -m set ! --match-set lb_link2 src,dstport,dst -j SET --add-set lb_link2 src,dstport,dst

	# Reload marks by ipset hash
	iptables -t mangle -A LB_GETMARK -m mark --mark 0x0/0x40000 -m set --match-set lb_link1 src,dstport,dst -j MARK --set-mark 0x40000/0x40000
	iptables -t mangle -A LB_GETMARK -m mark --mark 0x0/0x80000 -m set --match-set lb_link2 src,dstport,dst -j MARK --set-mark 0x80000/0x80000

	# Defining and save firewall marks
	iptables -t mangle -A LB_CNTRACK -o ${IF_GW1} -m mark --mark 0x0/0x40000 -j LB_SETMARK
	iptables -t mangle -A LB_CNTRACK -o ${IF_GW2} -m mark --mark 0x0/0x80000 -j LB_SETMARK
	iptables -t mangle -A LB_CNTRACK -m mark ! --mark 0x0/0xC0000 -j CONNMARK --save-mark --mask 0xc0000
	iptables -t mangle -A LB_POSTROUTING -j LB_CNTRACK

	# Reload all firewall marks
	# Use LB_OUTPUT chain for local access (Squid proxy, for example)
	iptables -t mangle -A LB_OUTPUT -m mark --mark 0x0/0xC0000 -j CONNMARK --restore-mark --mask 0xc0000
	iptables -t mangle -A LB_OUTPUT -m mark --mark 0x0/0xC0000 -j LB_GETMARK
	iptables -t mangle -A LB_PREROUTING -m mark --mark 0x0/0xC0000 -j CONNMARK --restore-mark --mask 0xc0000
	iptables -t mangle -A LB_PREROUTING -m mark --mark 0x0/0xC0000 -j LB_GETMARK
	# Set marks for incoming packet
	iptables -t mangle -A LB_PREROUTING -i ${IF_GW1} -m mark --mark 0x0/0x40000 -j MARK --set-mark 0x40000/0x40000
	iptables -t mangle -A LB_PREROUTING -i ${IF_GW2} -m mark --mark 0x0/0x80000 -j MARK --set-mark 0x80000/0x80000
}

lb_env_disable()
{
	# this will not call dbus client, so it wont block synonetd
	$SZF_SYNONETDTOOL --disable-lb-route-table
}

lb_route_rule_disable()
{
	ip route flush table link1-table
	ip route flush table link2-table
	ip route flush table lb-table

	ip rule del prio 203 table main
	ip rule del prio 204 lookup link1-table
	ip rule del prio 205 lookup link2-table
	ip rule del prio 206 lookup link1-table
	ip rule del prio 207 lookup link2-table
	ip rule del prio 208 lookup lb-table
}


lb_firewall_rules_disable()
{
	iptables -t mangle -F LB_GETMARK
	iptables -t mangle -F LB_SETMARK
	iptables -t mangle -F LB_CNTRACK
	iptables -t mangle -F LB_PREROUTING
	iptables -t mangle -F LB_POSTROUTING
	iptables -t mangle -F LB_OUTPUT

	ipset destroy lb_link1
	ipset destroy lb_link2
}

# check load balance route is exist or not
# @echo
#		0: exist
#		1: not exist, or any other issue might cause load balance failed
lb_is_route_exist()
{
	cat $SZF_RT_TABLES | grep lb-table &> /dev/null
	if [ 0 -ne $? ]; then
		echo 1
		return
	fi

	ip route show table lb-table &> /dev/null
	# output will be something like:
	# default  proto static
	#		nexthop via 10.11.71.95  dev eth0 weight 50
	#		nexthop via 118.165.159.211  dev ppp0 weight 50
	# and return 0

	# if not exist, will show something like:
	# Error: argument "lb" is wrong: table id value is invalid
	# and return 255

	if [ 0 -eq $? ]; then
		# route exist
		echo 0
	else
		echo 1
	fi

	return
}

# check load balance route setting has the same info as smart wan
# ex: load balance route set eth0 and eth0.1, but smart wan has changed to eth0 and ppp0
#     in this case, it will be judged as route exist, but incorrect
# @echo
#		0: correct
#		1: incorrect, or any other issue cause the check failed
lb_is_route_correct()
{
	cat $SZF_RT_TABLES | grep lb-table &> /dev/null
	if [ 0 -ne $? ]; then
		echo 1
		return
	fi

	local table_lb_ret=`ip route show table lb-table`
	# output will be something like:
	# default  proto static
	#		nexthop via 10.11.71.95  dev eth0 weight 50
	#		nexthop via 118.165.159.211  dev ppp0 weight 50

	local is_ifgw1_exist=1
	local is_ifgw2_exist=1

	echo $table_lb_ret | grep "nexthop via ${GW1} dev ${IF_GW1} weight ${WEIGHT1}" &> /dev/null
	is_ifgw1_exist=$?
	echo $table_lb_ret | grep "nexthop via ${GW2} dev ${IF_GW2} weight ${WEIGHT2}" &> /dev/null
	is_ifgw2_exist=$?

	if [ 0 -eq ${is_ifgw1_exist} -a 0 -eq ${is_ifgw2_exist} ]; then
		# route exist
		echo 0
		return
	fi

	echo 1
}

lb_conntrack_flush()
{
	# this is for load balance enabled, remove old nat conntrack
	for ifip in $IF_IP1 $IF_IP2; do
		if [ -z $ifip ]; then
			continue
		fi
		conntrack -D -n $ifip
	done

	conntrack -D --mark 0x40000/0x40000
	conntrack -D --mark 0x80000/0x80000
}

CMD=$1
case $CMD in
	--print-vars)
		# for debug used
		lb_vars_set
		lb_vars_print
		;;
	--lb-enable)
		lb_vars_set
		lb_vars_print
		lb_env_enable
		lb_route_rule_enable
		lb_firewall_rules_enable
		lb_conntrack_flush
		;;
	--lb-disable)
		lb_firewall_rules_disable
		lb_route_rule_disable
		lb_env_disable
		lb_conntrack_flush
		;;
	--lb-check-exist)
		lb_vars_set
		lb_is_route_exist
		;;
	--lb-check-correct)
		lb_vars_set
		lb_is_route_correct
		;;
	*)
		echo "unknown command $CMD"
		;;
esac

