#!@@GOODSH@@
# -*- sh -*-

set -e

: << =cut

=head1 NAME

netstat - Plugin to monitor network connections

=head1 CONFIGURATION

No configuration

=head1 AUTHOR

Unknown author

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

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

=cut

. "$MUNIN_LIBDIR/plugins/plugin.sh"

NETSTAT_CMD=netstat


if [ "$1" = "autoconf" ]; then
	if ( "$NETSTAT_CMD" -s 2>/dev/null >/dev/null ); then
		echo yes
		exit 0
	else
		if [ $? -eq 127 ]
		then
			echo "no (program $NETSTAT_CMD not found)"
			exit 0
		else
			echo "no (unknown netstat return value $?)"
			exit 0
		fi
	fi
fi

if [ "$1" = "config" ]; then

	echo 'graph_title Netstat'
	echo 'graph_args --base 1000 --logarithmic'
	echo 'graph_vlabel TCP connections'
	echo 'graph_category network'
	echo 'graph_period second'
	echo 'graph_info This graph shows the TCP activity of all the network interfaces combined.'
	echo 'active.label active'
	echo 'active.type DERIVE'
	echo 'active.min 0'
	echo 'active.max 50000'
	echo 'active.info The number of active TCP openings per second.'
	print_warning active
	print_critical active
	echo 'passive.label passive'
	echo 'passive.type DERIVE'
	echo 'passive.min 0'
	echo 'passive.max 50000'
	echo 'passive.info The number of passive TCP openings per second.'
	print_warning passive
	print_critical passive
	echo 'failed.label failed'
	echo 'failed.type DERIVE'
	echo 'failed.min 0'
	echo 'failed.max 50000'
	echo 'failed.info The number of failed TCP connection attempts per second.'
	print_warning failed
	print_critical failed
	echo 'resets.label resets'
	echo 'resets.type DERIVE'
	echo 'resets.min 0'
	echo 'resets.max 50000'
	echo 'resets.info The number of TCP connection resets.'
	print_warning resets
	print_critical resets
	echo 'established.label established'
	echo 'established.type DERIVE'
	echo 'established.min 0'
	echo 'established.max 50000'
	echo 'established.info The number of currently open connections.'
	print_warning established
	print_critical established
	exit 0
fi

"$NETSTAT_CMD" -s | awk '
/connection requests/     { print "active.value " $1 }
/connection accepts/      { print "passive.value " $1 }
/bad connection/          { print "failed.value " $1 }
/reset/                   { print "resets.value " $1 }
/connections established/ { print "established.value " $1 }'
