#!/bin/sh
# Copyright(c) 2011-2015 Shenzhen TP-LINK Technologies Co.Ltd.
# file     
# brief    
# author   Yuan Fengjia
# version  1.0.0
# date     23Dec15
# histry   arg 1.0.0, 23Dec15, Yuan Fengjia, Create the file.
[ ${INTERFACE:$((${#INTERFACE}-2))} == "v6" ] && exit 0
[ "$DEVICE" == "lo" ] && exit 0
[ "$INTERFACE" == "loopback" ] && exit 0

. /lib/functions.sh
. /lib/zone/zone_api.sh
local route_table_id_lan=29   		#use vnet route id 29
local route_tabke_priority_lan=29	#use vnet route priority 29
local route_table_id_lnk=41
local route_table_id_min=42
local route_table_id_max=210
local route_priority_base=20000
local link_priority_base=27

ROUTE_TABLE_ID="/tmp/route.id"
CACHE_TABLE_ID="/tmp/route.id.cache"
SPLIT_ACCESS_INIT_FILE="/tmp/split_access.init"
MAX_DNSSERVER_NUM=4

policy_table_alloc(){
    local iface=$2
	local cur_id
	
	[ ! -f $ROUTE_TABLE_ID ] && {
	    touch $ROUTE_TABLE_ID
		echo $route_table_id_min > $ROUTE_TABLE_ID
	}
	
	[ $iface == "lan" ] && {
	    local lan_cnt=`cat /etc/iproute2/rt_tables |grep -w $iface`
		[ -z "$lan_cnt" ] && lan_cnt=`cat ${CACHE_TABLE_ID} |grep -w $iface`
		if [ -z "$lan_cnt" ]; then 
			echo $route_table_id_lan $iface >> /etc/iproute2/rt_tables
			echo $route_table_id_lan $iface >> ${CACHE_TABLE_ID}
		fi
		
		export "$1=${route_table_id_lan}"
		return
	}
	
	echo "iface=$iface" >> /tmp/split_access.log
	local cnt=`cat /etc/iproute2/rt_tables |grep -w $iface`
	#local tmp="awk '/\s$iface$/{print}' /etc/iproute2/rt_tables"
	#local cnt=`eval $tmp`
	echo "cnt=$cnt" >> /tmp/split_access.log
	if [ -z "$cnt" ]; then
		[ -z "$cnt" ] && cnt=`cat ${CACHE_TABLE_ID} |grep -w $iface`
		if [ -z "$cnt" ]; then
			cur_id=`cat $ROUTE_TABLE_ID`
			cur_id=$((cur_id+1)) 
			if [ $cur_id -gt $route_table_id_max ]; then
					   cur_id=$route_table_id_min
			fi
			echo "cur_id=$cur_id"
			while [ 1 -eq 1 ]
			do
				#cur_id=$((cur_id+1)) 
				local id=`cat /etc/iproute2/rt_tables |grep -w $cur_id`
				if [ -z $id  ]; then
				   break;
				else 
				   cur_id=$((cur_id+1))
				   if [ $cur_id -gt $route_table_id_max ]; then
					   cur_id=$route_table_id_min
				   fi
				fi
			done
			echo $cur_id > ${ROUTE_TABLE_ID}
			echo $cur_id $iface >> ${CACHE_TABLE_ID}
		else
			cur_id=$(echo $cnt | cut -d' ' -f1)
		fi
		echo $cur_id $iface >> /etc/iproute2/rt_tables
		export "$1=${cur_id}"
	else
	    #cur_id=$(echo $cnt | cut -d' ' -f1)
		cur_id="duplication"
		export "$1=${cur_id}"
	fi
}

policy_table_free(){
    local iface=$1

    #sed -i "/\s${iface}$/d" /etc/iproute2/rt_tables
	 sed -i "/\<${iface}\>/d" /etc/iproute2/rt_tables
	#ip route flush table $iface &> /dev/null #need?
}

init_network_env() {
    #uci_revert_state splitaccess
	uci_set_state splitaccess core "" splitaccess_state
	uci_set_state splitaccess env "" splitaccess_env_state
}
	
generage_ifaces_env() {
	local if_list=$(zone_generage_ifaces_env)
	
	uci_set_state splitaccess env if_list "$if_list"
}

add_network_env() {
    local if=$1
    [ -n "$if" -a "$if" != "loopback" ] && {
		network_get_ipaddr if_ipaddr "$if"
		uci_toggle_state splitaccess env ${if}_ip "$if_ipaddr"
		network_get_subnet if_mask "$if"
		if_mask="${if_mask#*/}"
		uci_toggle_state splitaccess env ${if}_mask "$if_mask" 
		network_get_gateway if_gateway "$if"
		uci_toggle_state splitaccess env ${if}_gateway "$if_gateway" 
		network_get_dnsserver dns_server "$if"
		uci_toggle_state splitaccess env ${if}_dnsserver "$dns_server"
	}
}

del_network_env() {
    local if=$1
    [ -n "$if" -a "$if" != "loopback" ] && {
		uci_revert_state splitaccess env ${if}_ip 
		uci_revert_state splitaccess env ${if}_mask 
		uci_revert_state splitaccess env ${if}_gateway
		uci_revert_state splitaccess env ${if}_dnsserver
	}
}

lan_route_add() {
	local lanif="lan"
	
	local lan_device=$(zone_get_device_byif $lanif)
	local lan_ipaddr=$(uci_get_state splitaccess env ${lanif}_ip)
	local lan_mask=$(uci_get_state splitaccess env ${lanif}_mask)
	
	[ -z $lan_ipaddr ] && {
	    echo "lan_route_add: lan_ipaddr is invalid" >> /tmp/split_access.log
	    return;
	}
	if [ -z $lan_mask ]; then
	    echo "lan_route_add: lan_mask is invalid" >> /tmp/split_access.log
	    return;
	fi
	
	local lan_subnet=$(ipcalc -n ${lan_ipaddr}/${lan_mask})
	lan_subnet=${lan_subnet#*=}
	
	ip route add ${lan_subnet}/${lan_mask} dev $lan_device src $lan_ipaddr table $1
}

lan_route_del() {
	local lanif="lan"
	
	local lan_device=$(zone_get_device_byif $lanif)
	local lan_ipaddr=$(uci_get_state splitaccess env ${lanif}_ip)
	local lan_mask=$(uci_get_state splitaccess env ${lanif}_mask)
	
	[ -z $lan_ipaddr ] && {
	    echo "lan_route_del: lan_ipaddr is invalid" >> /tmp/split_access.log
	    return;
	}
	if [ -z $lan_mask ]; then
	    echo "lan_route_del: lan_mask is invalid" >> /tmp/split_access.log
	    return;
	fi
	
	local lan_subnet=$(ipcalc -n ${lan_ipaddr}/${lan_mask})
	lan_subnet=${lan_subnet#*=}
	
	ip route del ${lan_subnet}/${lan_mask} dev $lan_device src $lan_ipaddr table $1
}

up_event_handle() {
    local interface=$1

	policy_table_alloc table_id $interface
	echo "table_id=$table_id" >> /tmp/split_access.log
	
	[ $table_id == "duplication" ] && {
	    echo "duplication up event!!! Don't in this!!!" >> /tmp/split_access.log
		down_event_handle $interface
		policy_table_alloc table_id $interface
	    echo "table_id2=$table_id" >> /tmp/split_access.log
	}
	
	[ ! -f $SPLIT_ACCESS_INIT_FILE ] && {
	    touch $SPLIT_ACCESS_INIT_FILE
		init_network_env
	}

	generage_ifaces_env
	add_network_env $interface
	add_network_env lan
	
	local device=$(zone_get_device_byif $interface)
	local ipaddr=$(uci_get_state splitaccess env ${interface}_ip)
	local mask=$(uci_get_state splitaccess env ${interface}_mask)
	local gateway=$(uci_get_state splitaccess env ${interface}_gateway)
	local dns_server=$(uci_get_state splitaccess env ${interface}_dnsserver)
	local is_dslt=""
	[ "${device%-*}" == "dslt" ] && is_dslt="yes"
	
	echo "interface=$interface,device=$device,ipaddr=$ipaddr,mask=$mask,gateway=$gateway,dnsserver=$dns_server" >> /tmp/split_access.log
	
	#[ -z $gateway ] && {
	#    echo "up_event_handle: no gateway,don't do it!" >> /tmp/split_access.log
	#    return;
	#}

	[ -z $ipaddr -a -z $is_dslt ] && {
	    echo "up_event_handle: ipaddr is invalid" >> /tmp/split_access.log
	    return;
	}
	if [ -z $mask -a -z $is_dslt ]; then
	    echo "up_event_handle: mask is invalid" >> /tmp/split_access.log
	    return;
	fi

	[ "$interface" != "lan" -a "$interface" != "loopback" ] && {
		local zone

		if zone_dyn_name "$interface" zone || zone_dyn_vpn_name "$interface" zone;then
			ipset -! flush "${zone}_ifname"
			ipset -! flush "${zone}_ipv4"
			ipset -! add "${zone}_ifname" "$DEVICE"
			ipset -! add "${zone}_ipv4" "$ipaddr"
		else
			echo "up $interface get zone failed" >> /tmp/split_access.log
		fi
	}

	if [ -n "$is_dslt" ];then
		ip route add default dev $device table $interface
	else
		local subnet=$(ipcalc -n ${ipaddr}/${mask})
		subnet=${subnet#*=}
		echo "subnet=$subnet" >> /tmp/split_access.log

		ip route add ${subnet}/${mask} dev $device src $ipaddr table $interface
		[ -n "$gateway" ] && {
		    ip route add default via $gateway dev $device table $interface
		    ip route add $gateway dev $device src $ipaddr table link
		}
	fi
	#lan_route_add $interface

	local ext_target=""
	local ext_mask=""
	local ext_nexthop=""
	local ext_source=""
	local parent=$(uci get network.$interface.parent)
	ext_ifaces="$interface $parent"
	for ext_iface in $ext_ifaces
	do
		ext_target="";ext_mask="";ext_nexthop="";ext_source="";
		__network_ifstatus ext_routes "$ext_iface" "['route'][@.target!='0.0.0.0' && @.nexthop!='0.0.0.0' && !@.table].*"
		for ext_route in $ext_routes
		do
			[ -z "$ext_target" ] && { ext_target=$ext_route; continue; }
			[ -z "$ext_mask" ] && { ext_mask=$ext_route; continue; }
			[ -z "$ext_nexthop" ] && { ext_nexthop=$ext_route; continue; }
			[ -z "$ext_source" ] && ext_source=$ext_route
			ext_device=$(zone_get_device_byif $ext_iface)
			ip route add $ext_nexthop dev $ext_device table $interface
			ip route add $ext_target/$ext_mask via $ext_nexthop dev $ext_device table $interface
			ext_target="";ext_mask="";ext_nexthop="";ext_source="";
		done
	done

	. /lib/route/route_api.sh
	local metric=$(get_metric_from_iface $interface)
	local dnsserver_num=0

	# dns server target route
	for dns_s in $dns_server
	do
		let "dnsserver_num+=1"
		if [ $dnsserver_num -gt $MAX_DNSSERVER_NUM ]; then
			break
		fi
		local same_subnet=$(check_dns_ip_same_subnet ${ipaddr} ${mask} ${dns_s})
				#若dns server ip与wan接口在同一网段,无需指定下一跳
		if [ "$same_subnet" == "yes" ]
		then
			#echo "dns in same subnet $dns_s ${ipaddr}/${mask}" >/dev/console
			ip route add $dns_s  dev $device table $interface
			ip route add $dns_s  dev $device table link metric $metric
		else
			#echo "dns not in same subnet $dns_s ${ipaddr}/${mask}" >/dev/console
			ip route add $dns_s via $gateway dev $device table $interface
			ip route add $dns_s via $gateway dev $device table link metric $metric
		fi

	done
	touch "/tmp/online/route_${device}"
	local pri=$(($table_id+$route_priority_base))
	echo "pri=$pri" >> /tmp/split_access.log
	[ "$interface" != "lan" ] && ip rule add pref $pri from $ipaddr table $interface
	ip route flush cache
}

down_event_handle() {
    local interface=$1
	local device=$(zone_get_device_byif $interface)
	local ipaddr=$(uci_get_state splitaccess env ${interface}_ip)
	local mask=$(uci_get_state splitaccess env ${interface}_mask)
	local gateway=$(uci_get_state splitaccess env ${interface}_gateway)
	local dns_server=$(uci_get_state splitaccess env ${interface}_dnsserver)

	[ "$interface" != "lan" -a "$interface" != "loopback" ] && {
		local zone

		if zone_dyn_name "$interface" zone || zone_dyn_vpn_name "$interface" zone;then
			ipset -! flush "${zone}_ifname"
			ipset -! flush "${zone}_ipv4"
		fi
	}

	#echo `date`",down_event_handle:device=$device,ipaddr=$ipaddr,mask=$mask,gateway=$gateway" >> /tmp/split_access.log
	[ -z $ipaddr ] && {
	    echo "down_event_handle:ipaddr is invalid" >> /tmp/split_access.log
		policy_table_free $interface
	    return;
	}
	if [ -z $mask ]; then
	    echo "down_event_handle:mask is invalid" >> /tmp/split_access.log
		policy_table_free $interface
	    return;
	fi
	
	local subnet=$(ipcalc -n ${ipaddr}/${mask})
	subnet=${subnet#*=}
	#echo `date`",subnet=$subnet" >> /tmp/split_access.log

	ip route del ${subnet}/${mask} dev $device src $ipaddr table $interface
	[ -n "$gateway" ] && {
	    ip route del $gateway dev $device src $ipaddr table link
	    ip route del default via $gateway dev $device table $interface
	}

	. /lib/route/route_api.sh
	local metric=$(get_metric_from_iface $interface)
	local dnsserver_num=0

	for dns_s in $dns_server
	do
		let "dnsserver_num+=1"
		if [ $dnsserver_num -gt $MAX_DNSSERVER_NUM ]; then
			break
		fi
		local same_subnet=$(check_dns_ip_same_subnet ${ipaddr} ${mask} ${dns_s})
		#若dns server ip与wan接口在同一网段,无需指定下一跳
		if [ "$same_subnet" == "yes" ]
		then
			#echo "del dns in same subnet  $dns_s ${ipaddr}/${mask}" >/dev/console
			ip route del $dns_s  dev $device table $interface
			ip route del $dns_s  dev $device table link metric $metric
		else
			#echo "del dns not in same subnet $dns_s ${ipaddr}/${mask}" >/dev/console
			ip route del $dns_s via $gateway dev $device table $interface
			ip route del $dns_s via $gateway dev $device table link metric $metric
		fi

	done
	rm "/tmp/online/route_${device}" 2>&1 >/dev/null	
	lan_route_del $interface

	ip route flush table $interface
	
	ip rule del from $ipaddr table $interface
	
	policy_table_free $interface
	
	ip route flush cache
	
	generage_ifaces_env
	del_network_env $interface
}

reload_event_handle() {
	 	local if_list=$(uci_get_state splitaccess env if_list)
		
		for tmpif in ${if_list};do
			[ $tmpif != "lan" ] && {
				lan_route_del $tmpif
			}
        done
		
		generage_ifaces_env
		add_network_env lan
		for tmpif2 in ${if_list};do
			[ $tmpif2 != "lan" ] && {
				lan_route_add $tmpif2
			}
        done
}

update_event_handle() {
	down_event_handle $1
	up_event_handle $1
}

{
	flock -x 55
if [ -z $INTERFACE ]; then
    [ -z $DEVICE ] && {
		flock -u 55
		exit 0
	}
	INTERFACE=$(zone_get_iface_bydev $DEVICE)
fi

[ -z $INTERFACE ] && {
	flock -u 55
	exit 0
}

echo "ACTION=$ACTION,INTERFACE=$INTERFACE" >> /tmp/split_access.log

if [ $INTERFACE == "lan" ]; then
	if [ $ACTION == "ifup" ]; then
		reload_event_handle
	#else
	#	echo "Skip the event!" >> /tmp/split_access.log
	fi
	
	#flock -u 55
	#exit 0
fi

if ! ip rule | grep -q -e "from all lookup link" ; then
	sed -i "/${route_table_id_lnk} link/d" /etc/iproute2/rt_tables
	echo $route_table_id_lnk link >> /etc/iproute2/rt_tables
	ip rule add pref ${link_priority_base} table link
fi

if ! ip rule | grep -q -e "from all lookup lan" ; then
	policy_table_alloc table_id "lan"
	ip rule add pref ${route_tabke_priority_lan} table lan
fi

case "$ACTION" in
	ifup)
		up_event_handle $INTERFACE
	;;
	ifdown)
		down_event_handle $INTERFACE
	;;
	ifupdate)
		update_event_handle $INTERFACE
		echo "update event,do nothing" >> /tmp/split_access.log
	;;
esac
    flock -u 55
} 55<>/tmp/split_access.lock
