#!/usr/local/bin/bash
#
# if_
#
# HP-UX wildcard-plugin to fetch in and egress octet mibstats from NICs.
# To add a NIC, symlink if_<NIC> in munin-node's plugins confdir to this file,
# or try running, "munin-node-configure --families contrib --shell|grep if_|sh -"
# to have suggested (viz. configured) NICs linked automatically.
# Then check with e.g. "munin-run if_lan1 config" and "munin-run if_lan1"
# (select trailing "lan[0-9]" according to what "suggest" linked.
# Finally restart munin-node (e.g. /sbin/init.d/munin restart) and run checks from
# Munin server via telnet or netcat.
#
# contributed by <ralph.grothe@itdz-berlin.de>
#
#%# family=auto
#%# capabilities=autoconf suggest

PATH=/usr/bin:/usr/sbin
INTERFACE=$(basename "$0" | sed 's/^if_//g')
LANADMIN=/usr/sbin/lanadmin
LANSCAN=/usr/sbin/lanscan

if [[ $1 = autoconf ]]; then
    if ! uname -s|grep -qEi "hp-?ux"; then
        echo "no (OS doesn't seem to be HP-UX but reports as '$(uname -s)')"
        exit 0
    fi
    if [ -x "$LANADMIN" ]; then
        echo yes
        exit 0
    else
        echo "no ($LANADMIN not found)"
        exit 0
    fi
fi

if [[ $1 = suggest ]]; then
    # lanscan will list all usable NICs seen by the kernel
    if [ -x "$LANSCAN" ] \
            && seen=$("$LANSCAN" | awk '$3~/^[0-9]+$/&&$4=="UP"{print$5}'); then
        # but netstat will only list currently configured NICs
        if [[ -n $seen ]] && netstat -in|grep -q "$seen"; then
            # HP-UX names all NICs with leading string "lan" (afaik)
            # Note, in SG environments NICs with trailing asterisk
            # are usually standby NICs that often are used for heartbeat exchange,
            # why they are suitable for collecting data as well
            netstat -in|awk 'NR>1&&$1~/^lan[0-9]+\*?$/{print$1}'|tr -d \*
            exit 0
        fi
    fi
    exit 1
fi

if [[ $1 = config ]]; then
    echo "graph_order inbound outbound"
    echo "graph_title Interface $INTERFACE traffic"
    echo 'graph_args --base 1000'
    # shellcheck disable=SC2016
    echo 'graph_vlabel bits per ${graph_period} in (-) / out (+)'
    echo 'graph_category network'
    echo 'inbound.label received'
    echo 'inbound.type DERIVE'
    echo 'inbound.graph no'
    echo 'inbound.cdef inbound,8,*'
    echo 'inbound.min 0'
    echo 'outbound.label bps'
    echo 'outbound.type DERIVE'
    echo 'outbound.negative inbound'
    echo 'outbound.cdef outbound,8,*'
    echo 'outbound.min 0'
    exit 0
fi

/usr/sbin/lanadmin -g mibstats "${INTERFACE#lan}" \
    |awk '/(In|Out)bound Octets/{printf"%s.value %d\n",tolower($1),$NF}'
