#!/bin/sh

: << =cut

=head1 NAME

if_err_ - Wildcard-plugin to monitor errors on network interfaces

=head1 CONFIGURATION

=head2 WILDCARD PLUGIN

This is a wildcard plugin.  To monitor an interface, link
if_err_<interface> to this file. E.g.

  ln -s /usr/share/node/node/plugins-auto/if_err_ \
        /etc/munin/node.d/if_err_en0

...will monitor en0.

=head1 NOTES

Any device found in netstat -ib can be monitored. Examples include
en*, fw* and lo (the latter is not monitored by default).
Please note that aliases cannot be monitored with this plugin.

=head1 AUTHOR

Unknown author

=head1 LICENSE

Unknownl LICENSE

=head1 MAGIC MARKERS

 #%# family=auto
 #%# capabilities=autoconf suggest

=cut

INTERFACE=${0##*if_err_}

case $1 in
    autoconf)
        if command -v netstat >/dev/null; then
            echo yes
            exit 0
        else
            echo "no (netstat not found)"
            exit 0
        fi
        ;;
    suggest)
        if command -v netstat >/dev/null; then
            netstat -nib | awk '$3 ~ /Link/ && $1 !~ /(Name|lo|gif|stf)/ && $5 != "0" && $7 != "0" { print $1 }'
        fi
        exit 0
        ;;
    config)
        echo "graph_order down up collisions"
        echo "graph_title Interface $INTERFACE errors & collisions"
        echo 'graph_args --base 1000'
        # shellcheck disable=SC2016
        echo 'graph_vlabel packets in (-) / out (+) per ${graph_period}'
        echo 'graph_category network'
        echo "graph_info This graph shows the amount of errors and collisions on the $INTERFACE network interface."
        echo 'down.label packets'
        echo 'down.type COUNTER'
        echo 'down.graph no'
        echo 'down.warning 1'
        echo 'up.label packets'
        echo 'up.type COUNTER'
        echo 'up.negative down'
        echo 'up.warning 1'
        echo "up.info Errors of the $INTERFACE interface."
        echo 'collisions.label Collisions'
	echo 'collisions.type COUNTER'
        exit 0
        ;;
esac

# Name  Mtu   Network       Address            Ipkts Ierrs     Ibytes    Opkts Oerrs     Obytes  Coll
# en1   1500  <Link#5>    00:17:f2:e8:f8:3c 11548082 38116  702690133 22938005   170 16013565627     0
netstat -nib -I "$INTERFACE" | awk '$3 ~ /Link/ { print "down.value " $6 "\nup.value " $9 "\ncollisions.value " $11 }'
