#!/bin/sh

############
# CHANGELOG
#===========
# 2010/03/05    CRMS00218043    Thanh lam NGUYEN
#               Change to new "eth" syntax
################################
esc=$'\x1b' attr="$esc[32m" default="$esc[0m" PS4="+$$: "

allinfo="speed duplex collisions crcerrors broadcast"
#######################
: "Function definition"
#######################
help() {
    : "${attr}help start (arg: $*)${default}"
    local scriptname=${0##*/}
    echo ""
    echo "Syntax: $scriptname cpu"
    echo "     or $scriptname lan|pc [speed|duplex|collisions|crcerrors|broadcast]"
    echo ""
    echo "This script returns the requested information."
    echo ""
    : "${attr}help end${default}"
    return 0
}

##############################
: "End of function definition"
##############################

: "${attr}Read system configuration${default}"
. /etc/sysconfig
. $DEBUGBINPATH/.functions

RET=$OK

: "${attr}Command line arguments processing...${default}"
while [[ x$1 != x ]]; do
    case "$1" in
        -h|--help)
            help
            RET=$OK
            EXITSCRIPT
        ;;
        cpu)
            cpu=1
            break
        ;;
        lan)
            dev=$ETHLCFG_LAN
        ;;
        pc)
            dev=$ETHLCFG_PC
        ;;
        speed|duplex|collisions|crcerrors|broadcast)
            info="$info $1"
        ;;
        *)
            help
            RET=$NOK
            EXITSCRIPT
        ;;
    esac
    shift
done


: "${attr}check arguments...${default}"
[[ -z "${info:-}" ]] && info=$allinfo
if [[ ${cpu:-0} -eq 0 ]] && [[ -z "${dev:-}" ]]; then
    help
    RET=$NOK
    EXITSCRIPT
fi

: "${attr}fetch the informations....${default}"
if [[ ${cpu:-0} -eq 1 ]]; then
    echo "DOS packet drop: $(getmib snmpBcmDosDropCount)"
    RET=$OK
else
# CRMS00218043
    dev_idle=$(eth link $dev '?' | awk '/down/{print "1"}/up/{print "0"}')
# CRMS00218043 END
    for reg in $info; do
        data="$(printf "%-10s" $reg)"
        case "$reg" in
            speed) : "${attr}speed${default}"
# CRMS00218043
                [[ ${dev_idle} -eq 1 ]] && data="$data idle" || data="$data $(eth speed $dev '?')"
# CRMS00218043 END
            ;;
            duplex) : "${attr}duplex${default}"
# CRMS00218043
                [[ ${dev_idle} -eq 1 ]] && data="$data idle" || data="$data $(eth duplex $dev '?' | awk '/Full/{print "full"}/Half/{print "half"}')"
# CRMS00218043 END
            ;;
            collisions) : "${attr}collisions${default}"
                data="$data $(getmib $dev TxCollisions)"
            ;;
            crcerrors) : "${attr}crcerrors${default}"
                data="$data $(($(getmib $dev RxCRCAlignErrors) - $(getmib $dev RxAlignmentErrors)))"
            ;;
            broadcast) : "${attr}broadcast${default}"
                data="$data $(getmib snmpEtherStatsBroadcastPkts)"
            ;;
            *)
                continue
            ;;
        esac
        echo "$data"
    done
fi
RET=$OK
EXITSCRIPT
