#!/bin/bash

basepath=$(cd `dirname $0`; pwd)
filename=`echo $0|awk -F '/' '{print $NF}'`
tmpfile="$basepath/tmp/${filename}.tmp"
tmpdir=`dirname $tmpfile`
[ ! -d $tmpdir ] && mkdir $tmpdir
now=$(date +%s)

if [ ! -d "/sys/class/net/bond0" ]; then
	exit 0
fi

bond_nic1=`cat /sys/class/net/bond0/bonding/slaves | cut -f1 -d' '`
bond_nic2=`cat /sys/class/net/bond0/bonding/slaves | cut -f2 -d' '`

bond_nic=$(echo $bond_nic1 $bond_nic2)

if [[ ! -n $bond_nic ]];then
	exit 0
fi

addr=${bond_nic}

collect() {
        ifname=$1
	value=$(cat /sys/class/net/$ifname/bonding_slave/link_failure_count)

	#查看是否有历史值
	old=`cat $tmpfile|grep "^${ifname}|"`
	if [ "$old" == "" ];then
		echo "$ifname|$value|$now" >> $tmpfile
	else
		oldvalue=`echo $old|awk -F '|' '{print $2}'`
		# oldvalue为空时，oldvalue=value
		if [ "$oldvalue" == "" ];then
			oldvalue=$value
		fi
		oldts=`echo $old|awk -F '|' '{print $3}'`
                ratevalue=$(($value-$oldvalue))
		#ratevalue=`echo "($value-$oldvalue)/($now-$oldts)"|bc`
		#删除老值插入新值
		sed -i "/${ifname}|/d" $tmpfile
		echo "$ifname|$value|$now" >> $tmpfile
		#插入结果
		sed -i "/iface=$ifname/d" $tmpfile
		if [ "$ratevalue" -ge 0 ];then
			echo "{\"value\":$ratevalue,\"tags\":\"iface=$ifname\"}" >> $tmpfile
		fi
	fi
}

for i in $addr
do
	collect $i
done

for i in `cat $tmpfile|grep "iface="`
do
	if [ "$ret" == "" ];then
		ret=$i
	else
		ret="$ret,$i"
	fi
done
#删除结果,防止在没收集到数据时任然保留了上次的脏数据
sed -i "/iface=/d" $tmpfile
if [ "$ret" == "" ];then
	exit 1
fi
#输出结果
echo "[$ret]"
exit 0
#[{"value":0,"tags":"iface=eth1"},{"value":0,"tags":"iface=eth3"}]
