#!/bin/sh

interval=2
iface=""

do_cycle_stats()
{
	local iface="$1"
	local interval="$2"

	[ -z "$iface" ] && return 1

	while true; do
		stats_line=`grep "^[ \t]*${iface}:" /proc/net/dev | sed 's/^.\+: *//'`
		cpu_line=`grep '^cpu ' /proc/stat`
		[ -z "$stats_line" ] && return 1
		[ -z "$cpu_line" ] && return 1

		local rx_bytes=`echo "$stats_line" |awk '{print $1}'`
		local rx_packets=`echo "$stats_line" |awk '{print $2}'`
		local rx_drop=`echo "$stats_line" |awk '{print $4}'`

		local tx_bytes=`echo "$stats_line" |awk '{print $9}'`
		local tx_packets=`echo "$stats_line" |awk '{print $10}'`

		local si_jfs=`echo "$cpu_line" |awk '{printf("%.f",$8)}'`
		local cpu_jfs=`echo "$cpu_line" |awk '{printf("%.f",$2+$3+$4+$5+$6+$7+$8)}'`

		if [ ! -z "$__rx_packets" ]; then
			local rx_bytes_per_sec=`expr \( $rx_bytes - $__rx_bytes \) / $interval`
			local rx_packets_per_sec=`expr \( $rx_packets - $__rx_packets \) / $interval`
			local rx_drop_per_sec=`expr \( $rx_drop - $__rx_drop \) / $interval`
			local tx_bytes_per_sec=`expr \( $tx_bytes - $__tx_bytes \) / $interval`
			local tx_packets_per_sec=`expr \( $tx_packets - $__tx_packets \) / $interval`
			local total_bytes_per_sec=`expr $rx_bytes_per_sec + $tx_bytes_per_sec`
			local softirq_percent=`echo $si_jfs $__si_jfs $cpu_jfs $__cpu_jfs |awk '{print ($1-$2)/($3-$4)*100}'`
			local current_date=`date '+%H:%M:%S'`
			printf "[%s] %s:  TX: %9s / %5s  RX: %9s / %5s  Drop: %2s  Total: %9s  Softirq: %.1f%%\n" \
				"$current_date" "$iface" "$tx_bytes_per_sec" "$tx_packets_per_sec" \
				"$rx_bytes_per_sec" "$rx_packets_per_sec" "$rx_drop_per_sec" "$total_bytes_per_sec" "$softirq_percent"
		fi

		local __rx_bytes=$rx_bytes
		local __rx_packets=$rx_packets
		local __rx_drop=$rx_drop
		local __tx_bytes=$tx_bytes
		local __tx_packets=$tx_packets
		local __si_jfs=$si_jfs
		local __cpu_jfs=$cpu_jfs

		sleep $interval
	done

}

do_show_help()
{
	echo "Usage: $0 <dev_name> [-i interval]"
}

while [ ! -z "$1" ]; do
	case "$1" in
		"-i"|"-t")
			interval="$2"
			shift 2
			;;
		*)
			iface="$1"
			shift 1
			;;
	esac
done

expr "$interval" + 1 >/dev/null 2>&1 || { do_show_help; exit 1; }
[ -z "$iface" -o -z "$interval" ] && { do_show_help; exit 1; }

do_cycle_stats "$iface" "$interval"
exit $?
