#!/bin/bash

itemkey=$1
IFNAME=$2

function process() {
	# echo process, sort 20 by time 
    ps aux | sort -rn -k10 | head -20 | awk '
	BEGIN { ORS = ""; print " [ "}
	{ printf "%s{\"user\": \"%s\", \"pid\": \"%s\", \"cpu\": \"%s\", \"mem\": \"%s\", \"stat\": \"%s\", \"time\": \"%s\", \"command\": \"%s\"}",
	      separator, $1, $2, $3, $4, $8, $10, $11
	  separator = ", "
	}
	END { print " ] " }';
}

function receive() {
	# echo total receive
	# this script is net receive packets

	diskarray=(`cat /proc/net/dev | tail -n +3 | awk '{print $1}' | cut -d ":" -f 1`)
	length=${#diskarray[@]}

	receive=0
	for ((i=0;i<$length;i++))
	do
		j=`cat /proc/net/dev | grep ${diskarray[$i]}  | awk '{print $3}'`
		receive=$(($receive+$j))
	done

	echo $receive
}

function transmit() {
	# echo total transmit
	# this script is net receive packets
	diskarray=(`cat /proc/net/dev | tail -n +3 | awk '{print $1}' | cut -d ":" -f 1`)
	length=${#diskarray[@]}
	transmit=0
	for ((i=0;i<$length;i++))
	do
		j=`cat /proc/net/dev | grep ${diskarray[$i]}  | awk '{print $10}'`
		transmit=$(($transmit+$j))
	done

	echo $transmit
}


function totalPackets() {
	# echo total Packets
	# this script is net total packets
	diskarray=(`cat /proc/net/dev | tail -n +3 | awk '{print $1}' | cut -d ":" -f 1`)
	length=${#diskarray[@]}
	transmit=0
	receive=0
	for ((i=0;i<$length;i++))
	do
		j=`cat /proc/net/dev | grep ${diskarray[$i]}  | awk '{print $10}'`
		v=`cat /proc/net/dev | grep ${diskarray[$i]}  | awk '{print $3}'`
		transmit=$(($transmit+$j))
		receive=$(($receive+$v))
	done

	totalPackets=0
	totalPackets=$(($totalPackets+$transmit+$receive))
	echo $totalPackets
}


function speed() {
	# echo speed
    if [ $IFNAME == "lo" ] ; then
        echo 0
    else
        cat /sys/class/net/$IFNAME/speed
    fi
    return
}

function address() {
	# echo address
	cat /sys/class/net/$IFNAME/address
}

case "$1" in
        process)
            process
            ;;
        receive)
            receive
            ;;
        transmit)
            transmit
            ;;
        totalPackets)
			totalPackets
			;;
        speed)
            speed
            ;;
        address)
            address
            ;;  
        *)
        echo $"Usage $0 { process|receive|transmit|totalPackets|speed|address}"
		exit
esac