#!/bin/bash

tmpfile="/dev/shm/$(basename $0).tmp"
now=$(date +%s)

if [[ ! -d /proc/net/bonding ]];then
    exit 0
fi

declare -a info
for bond in `ls /proc/net/bonding`;
do

    for netcard in $(cat /sys/class/net/$bond/bonding/slaves)
    do
        value=$(cat /sys/class/net/$netcard/bonding_slave/link_failure_count)

        #查看是否有历史值
        old=`cat $tmpfile|grep "^${netcard}|"`
        if [ "$old" == "" ];then
            echo "$netcard|$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))
            #删除老值插入新值
            sed -i "/${netcard}|/d" $tmpfile
            echo "$netcard|$value|$now" >> $tmpfile
            info[${#info[@]}]='{"value":'$ratevalue',"tags":"iface='$netcard',bond='$bond'"}'
        fi
    done
done

function join_by {
    local d=${1-} f=${2-}
    if shift 2; then
        printf %s "$f" "${@/#/$d}"
    fi
}

echo -n '['
join_by , ${info[@]}
echo ']'

