#!/bin/sh

return

state_dir="/tmp/balance/"
pre_file="/tmp/balance/pre_state"
cur_file="/tmp/balance/cur_state"

online_file="/tmp/online/state"

event_file="/tmp/balance/.iface_event"

LTE_PTYPE="5"
LTE_DEV_NAME="usb0"

. /lib/zone/zone_api.sh
. /lib/balance/api.sh

INTERVAL=2

#check if there is a LTE port
check_lte()
{
	local ptype=`uci -q get lports.usb1.ptype`
	if [ -n "$ptype" -a "$ptype" == "${LTE_PTYPE}" ];then
		LB_HAS_LTE="1"
	else
		LB_HAS_LTE="0"
	fi
}

change_default_route()
{
	local default=`ip route | awk 'FNR==1 {print $1}'`
	local dev_1=`ip route | awk 'FNR==1 {print $5}'`
	local dev_stat=`grep "${dev_1}=" "$online_file" | awk 'FNR==1' | awk -F "=" '{print $2}'`
	local change_flag="0"
	local dev_on=`grep "=on.*" "$online_file" | awk -F "=" '{print $1}'`
	[ -z "$dev_on" ] && return
	#如果LET是default，且有其他wan是online，需要把其他wan置为default
	[ "$LB_HAS_LTE" == "1" -a "${dev_1}" == "$LTE_DEV_NAME" -a "$dev_stat" == "on" ] && {
		if [ "x${dev_on}" != "x${LTE_DEV_NAME}" ];then   #不止有usb0 online
			change_flag="1"
		fi
	}
        #echo "change_default_route dev_on:${dev_on}, dev_1:${dev_1}, dev_stat:${dev_stat}, change_flag:$change_flag, LB_HAS_LTE=$LB_HAS_LTE"  > /dev/console
        [ "$default" == "default" ] && [ "$dev_stat" == "off" -o "$change_flag" == "1" ] && {
		for dev in ${dev_on};do
			[ "$LB_HAS_LTE" != "1" -o "${dev}" != "$LTE_DEV_NAME" -o "${dev_on}" == "$LTE_DEV_NAME" ] && {
				local gw=`ip route | grep default | grep $dev | awk -F ' ' '{printf $3}' `
				if [ -n "$gw" ]; then
					# skip if is LTE
					route del default gw $gw $dev
					route add default gw $gw $dev
					return
				fi
			}

		done
        }
}

get_cur_state()
{
	local key="$1"

	[ -f $cur_file ] || return 0

	grep "^${key}=.*" "$cur_file" 2>&1 >/dev/null || {
		return 1
	}

	echo "`cat $cur_file |grep "\<${key}\>" |cut -d '=' -f 2`"
}

get_pre_state()
{
	local key="$1"

	[ -f $pre_file ] || return 0

	grep "^${key}=.*" "$pre_file" 2>&1 >/dev/null || {
		return 1
	}

	echo "`cat $pre_file |grep "\<${key}\>" |cut -d '=' -f 2`"
}

#$1:device
device_to_iface()
{
	iface=`zone_get_iface_bydev $1`
	zone=`zone_get_zone_byif $iface`

	if [ "$zone" == "VPN" ];then
		zone=$iface
	fi

	echo "$zone"
}

if [ -e /var/run/balance_loop.pid ] ; then
	kill $(cat /var/run/balance_loop.pid) &> /dev/null
	rm /var/run/balance_loop.pid &> /dev/null
fi

echo "$$" > /var/run/balance_loop.pid

[ -z "$LB_HAS_LTE" ] && check_lte 
#file format: device=state
#like eth0=on
while true; do
	[ ! -e $state_dir ] && mkdir -p $state_dir
	
	#调整路由优先级
	change_default_route

	#fast check
	if [ -f $online_file -a -f $cur_file -a -f $pre_file ]; then
		if [ -z "$(diff -q $online_file $cur_file)" -a -z "$(diff -q $cur_file $pre_file)" ]; then
			has_event=""
			for dev in $(sed 's/=.*//g' $online_file)
			do
				if grep -q $dev $event_file ; then
					has_event="yes"
					break
				fi
			done
			[ -z "${has_event}" ] && {
				sleep $INTERVAL
				continue
			}
		fi
	fi

	#slow check
	if [ -f $online_file ];then
		cp $online_file $cur_file -f

		if [ -f $pre_file ];then
			cat $pre_file | while read line
			do
				if [ -n "$line" ];then
					device=`echo $line | cut -d '=' -f 1`
					pre_state=`echo $line | cut -d '=' -f 2`

					cur_state=`get_cur_state $device`

					#modify the device state
					if [ -n "$cur_state" ];then
						if [ "$pre_state" != "$cur_state" ];then
							iface=`device_to_iface $device`

							if [ "$cur_state" == "on" ]; then
								echo "modify iface=[$iface], dev=[$device], up" >> /tmp/balance/balance_loop
								env -i ACTION=ifup INTERFACE=$iface DEVICE=$device /sbin/hotplug-call balance
								
							elif [ "$cur_state" == "off" ]; then
								echo "modify iface=[$iface], dev=[$device], down" >> /tmp/balance/balance_loop
								env -i ACTION=ifdown INTERFACE=$iface DEVICE=$device /sbin/hotplug-call balance							
							fi
						#when the up/down event happen between online check twice on
						elif [ "$cur_state" == "on" ]; then
							iface_event=`balance_iface_get_event $device`

							if [ "$iface_event" == "down" -o "$iface_event" == "up" ];then
								iface=`device_to_iface $device`
								echo "iface=[$iface], dev=[$device], $iface_event twice just for test...." >> /tmp/balance/balance_loop
								env -i ACTION=ifup INTERFACE=$iface DEVICE=$device /sbin/hotplug-call balance
								balance_iface_del_event $device							
							fi
						#when the up/down event happen between offline, update
						elif [ "$cur_state" == "off" ]; then
							iface_event=`balance_iface_get_event $device`
							if [ "$iface_event" == "up" -o "$iface_event" == "down" ]; then
								iface=`device_to_iface $device`
								echo "dev=[$device] offline $iface_event, update" >> /tmp/balance/balance_loop
								env -i ACTION=ifdown INTERFACE=$iface DEVICE=$device /sbin/hotplug-call balance
								balance_iface_del_event $device
							fi
						fi
					else
						#del old dev	

						iface=`device_to_iface $device`
						echo "del iface=[$iface], dev=[$device]" >> /tmp/balance/balance_loop
						env -i ACTION=ifdown INTERFACE=$iface DEVICE=$device /sbin/hotplug-call balance		
					fi
				fi
			done
		fi

		#add new dev
		if [ -f $cur_file ];then
			cat $cur_file | while read line
			do
				if [ -n "$line" ];then
					device=`echo $line | cut -d '=' -f 1`
					cur_state=`echo $line | cut -d '=' -f 2`

					pre_state=`get_pre_state $device`

					if [ -z "$pre_state" ];then

						iface=`device_to_iface $device`

						if [ "$cur_state" == "on" ]; then
							echo "add iface=[$iface], dev=[$device], up" >> /tmp/balance/balance_loop
							env -i ACTION=ifup INTERFACE=$iface DEVICE=$device /sbin/hotplug-call balance
							
						elif [ "$cur_state" == "off" ]; then
							echo "add iface=[$iface], dev=[$device], down" >> /tmp/balance/balance_loop
							env -i ACTION=ifdown INTERFACE=$iface DEVICE=$device /sbin/hotplug-call balance
							
						fi
					fi
				fi
			done
		fi
	fi

	cp $cur_file $pre_file -f

	sleep $INTERVAL
done

