#!/bin/bash

# nstats.sh

function net_exit ()
 {
  echo "Network Interface does not exists: ${1}"
  exit 1
 }

function byte_rep ()
 {
  bytes="${1}"

  if (($bytes<1024)); then
   echo -ne "$bytes B"
   return
  elif (($bytes<(1024*1024))); then
   KiB=$(($bytes/1024))
   tmp=$(($KiB*1024))
   B=$((($bytes-$tmp)*1000/1024))
   echo -ne "${KiB}.${B} KiB"
   return
  elif (($bytes<(1024*1024*1024))); then
   MiB=$(($bytes/1024/1024))
   tmp=$(($MiB*1024*1024))
   KiB=$((($bytes-$tmp)/1024*1000/1024))
   echo -ne "${MiB}.${KiB} MiB"
   return
  elif (($bytes<(1024*1024*1024*1024))); then
   GiB=$((${bytes}/1024/1024/1024))
   tmp=$(($GiB*1024*1024*1024))
   MiB=$(((${bytes}-$tmp)/1024/1024*1000/1024))
   echo -ne "${GiB}.${MiB} GiB"
   return
  elif (($bytes<(1024*1024*1024*1024*1024))); then
   TiB=$((${bytes}/1024/1024/1024/1024))
   tmp=$(($TiB*1024*1024*1024*1024))
   GiB=$(((${bytes}-$tmp)/1024/1024/1024*1000/1024))
   echo -ne "${TiB}.${GiB} TiB"
   return
  fi
 }

function pkt_rep ()
 {
  pkts="${1}"

  if (($pkts<1024)); then
   echo -ne "$pkts p"
   return
  elif (($pkts<(1024*1024))); then
   Kip=$(($pkts/1024))
   tmp=$(($Kip*1024))
   B=$((($pkts-$tmp)*1000/1024))
   echo -ne "${Kip}.${B} Kip"
   return
  elif (($pkts<(1024*1024*1024))); then
   Mip=$(($pkts/1024/1024))
   tmp=$(($Mip*1024*1024))
   Kip=$((($pkts-$tmp)/1024*1000/1024))
   echo -ne "${Mip}.${Kip} Mip"
   return
  fi
 }

PAR1="$1"

PARN="$#"

[ $PARN -lt 1 ] && echo "Give the network device as argument" && exit 1

ND="/sys/class/net/${PAR1}"

[ -d "${ND}" ] && true || net_exit "${PAR1}"

echo

RBF="${ND}/statistics/rx_bytes"
RPF="${ND}/statistics/rx_packets"
TBF="${ND}/statistics/tx_bytes"
TPF="${ND}/statistics/tx_packets"

SRBT=`cat ${RBF}`
SRPT=`cat ${RPF}`
STBT=`cat ${TBF}`
STPT=`cat ${TPF}`

PRBT="${SRBT}"
PRPT="${SRPT}"
PTBT="${STBT}"
PTPT="${STPT}"

while true; do
 sleep 1s
 CRBT=`cat ${RBF}`
 CRPT=`cat ${RPF}`
 CTBT=`cat ${TBF}`
 CTPT=`cat ${TPF}`
 CRB="`byte_rep $((${CRBT}-${PRBT}))`"
 CRP="`pkt_rep $((${CRPT}-${PRPT}))`"
 CTB="`byte_rep $((${CTBT}-${PTBT}))`"
 CTP="`pkt_rep $((${CTPT}-${PTPT}))`"
 CRBST="`byte_rep $((${CRBT}-${SRBT}))`"
 CTBST="`byte_rep $((${CTBT}-${STBT}))`"
 echo -ne "rx: $CRB/s    $CRP/s    $CRBST    tx: $CTB/s    $CTP/s    $CTBST    \r"
 PRBT=$CRBT
 PRPT=$CRPT
 PTBT=$CTBT
 PTPT=$CTPT
done
