#!/bin/sh
# Check_MK Agent for OpenBSD
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2014             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

# Author: Lars Michelsen <lm@mathias-kettner.de>
#         Florian Heigl <florian.heigl@gmail.com>
#	  Christian Zigotzky <chzigotzky@xenosoft.de>

# NOTE: This agent has been adapted from the Check_MK FreeBSD agent.

# Remove locale settings to eliminate localized outputs where possible
export LC_ALL=C
unset LANG

export MK_LIBDIR="/usr/lib/check_mk_agent"
export MK_CONFDIR="/etc/check_mk"

# Optionally set a tempdir for all subsequent calls
#export TMPDIR=

# Make sure, locally installed binaries are found
PATH=$PATH:/usr/local/bin

# All executables in PLUGINSDIR will simply be executed and their
# ouput appended to the output of the agent. Plugins define their own
# sections and must output headers with '<<<' and '>>>'
PLUGINSDIR=$MK_LIBDIR/plugins

# All executables in LOCALDIR will by executabled and their
# output inserted into the section <<<local>>>. Please refer
# to online documentation for details.
LOCALDIR=$MK_LIBDIR/local


# close standard input (for security reasons) and stderr
if [ "$1" = -d ]
then
    set -xv
else
    exec <&- 2>/dev/null
fi

echo '<<<check_mk>>>'
echo Version: 1.5.0p11
echo AgentOS: openbsd

osver="$(uname -r)"

echo '<<<df>>>'
df -kPt ffs | sed -e 's/^\([^ ][^ ]*\) \(.*\)$/\1 ffs \2/' | sed 1d

# processes including username, without kernel processes
echo '<<<ps>>>'
COLUMNS=10000
ps ax -o user,vsz,rss,pcpu,command | sed -e 1d -e 's/ *\([^ ]*\) *\([^ ]*\) *\([^ ]*\) *\([^ ]*\) */(\1,\2,\3,\4) /'

echo '<<<cpu>>>'
echo `sysctl -n vm.loadavg | tr -d '{}'` `top -b -n 1 | grep -E '^[0-9]+ processes' | awk '{print $3"/"$1}'` `sysctl -n hw.ncpu`

echo '<<<uptime>>>'
echo `date +%s` - `sysctl -n kern.boottime | cut -d' ' -f 4,7 | tr ',' '.' | tr -d ' '` | bc

echo "<<<mem>>>"
MEM_FREE=$(vmstat | tail -n1 | awk '{ print $5 }')
MEM_TOTAL=$(sysctl hw.usermem | cut -d= -f2)
MEM_TOTAL=$(echo $MEM_TOTAL/1024 | bc)

SWAPCTL_OUTPUT=$(swapctl -k -s)
SWAP_FREE=$(echo $SWAPCTL_OUTPUT | awk '{ print $7 }')
SWAP_TOTAL=$(echo $SWAPCTL_OUTPUT | awk '{ print $2 }')

# if there is no swap space swap values are 0
if [ -z "$SWAPCTL_OUTPUT" ]
        then
        SWAP_FREE=0
        SWAP_TOTAL=0
fi

echo "MemTotal:\t" $MEM_TOTAL kB
echo "MemFree:\t" $MEM_FREE kB
echo "SwapTotal:\t" $SWAP_TOTAL kB
echo "SwapFree:\t" $SWAP_FREE kB

echo '<<<lnx_if:sep(58)>>>'
# MC= MAC address
# BI= Bytes in
# PI= Packets in
# EI= Errors in
# EO= Errors out
# BO= Bytes out
# PO= Packets out
# CO= Colls
# NI= Number of interfaces
# INTERFACES= Array of interfaces

set -A INTERFACES
set -A MC
set -A BI
set -A BO
set -A PI
set -A PO
set -A EI
set -A EO
set -A CO

NI=0
# special (lo/pfsync/pflog/enc) and inactive (*) interfaces are not needed
NETSTAT_OUTPUT=$(netstat -in | grep '<Link>' | egrep -v "\*|lo|pfsync|enc")
NETSTAT_OUTPUT_BYTES=$(netstat -inb | grep '<Link>' | egrep -v "\*|lo|pfsync|enc")

# adjust internal field separator to get lines from netstat and backup it before
OFS=$IFS
IFS='
'
# collect netstat values and interface number
for NS in $NETSTAT_OUTPUT
    do
    NI=$(($NI+1))
    INTERFACES[$NI]=$(echo $NS | awk '{print $1}')
    MC[$NI]=$(echo $NS | awk '{print $4}')
    PI[$NI]=$(echo $NS | awk '{print $5}')
    EI[$NI]=$(echo $NS | awk '{print $6}')
    PO[$NI]=$(echo $NS | awk '{print $7}')
    EO[$NI]=$(echo $NS | awk '{print $8}')
    CO[$NI]=$(echo $NS | awk '{print $9}')
done

# need NIC counter again for byte values - reset it
NI=0
for NS in $NETSTAT_OUTPUT_BYTES
    do
    NI=$(($NI+1))
    BI[$NI]=$(echo $NS | awk '{print $5}')
    BO[$NI]=$(echo $NS | awk '{print $6}')
done

# what is this for?
[ "${NI}" -ge 1 ] || NI=15

# jot is OpenBSD "range"
for i in $(jot $NI)
    do
    echo "${INTERFACES[$i]}:${BI[$i]} ${PI[$i]} ${EI[$i]} 0 0 0 0 0 ${BO[$i]} ${PO[$i]} ${EO[$i]} 0 0 ${CO[$i]} 0 0"
done

for IF in $(jot $NI)
	do
	echo \[${INTERFACES[$IF]}\]

	IFCONFIG_OUTPUT=$(ifconfig ${INTERFACES[$IF]})
	for IO in $IFCONFIG_OUTPUT
		do
		# Speed
		SP=$(echo "$IO" | egrep "media:.*base" | cut -d\( -f2 | cut -db -f1)
		if [ "$SP" ]
			then
			echo "\tSpeed: "$SP"Mb/s"
		fi
		# Detect duplexity - in reality only available for physical devices but
		# virtual ones like CARP devices will get at least a half duplex
		if [ "$(echo "$IO" | egrep "media:.*full-duplex")" ]
			then
			echo "\tDuplex: Full"
		elif [ "$(echo "$IO" | grep "media:" | grep -v "full-duplex")" ]
			then
			echo "\tDuplex: Half"
		fi
		# Auto-negotiation
		if [ "$(echo "$IO" | egrep "media:.*autoselect")" ]
			then
			echo "\tAuto-negotiation: on"
		elif [ "$(echo "$IO" | grep "media:" | grep -v "autoselect")" ]
			then
			echo "\tAuto-negotiation: off"
		fi
		# Detect detected link
		if [ "$(echo "$IO" | grep "status:" | egrep "active|backup|master")" ]
			then
			echo "\tLink detected: yes"
		fi
	done

	echo "\tAddress: "${MC[$IF]}

done

# reset IFS to default
IFS=$OFS

# IPMI-Data (Fans, CPU, temperature, etc)
# needs the sysutils/ipmitool and kldload ipmi.ko
if which ipmitool >/dev/null ; then
    echo '<<<ipmi>>>'
    ipmitool sensor list \
        | grep -v 'command failed' \
        | sed -e 's/ *| */|/g' -e "s/ /_/g" -e 's/_*$//' -e 's/|/ /g' \
        | egrep -v '^[^ ]+ na ' \
        | grep -v ' discrete '
fi

if which mailq >/dev/null 2>&1 && getent passwd postfix >/dev/null 2>&1; then
  echo '<<<postfix_mailq>>>'
  mailq | tail -n 6
fi


# Einbinden von lokalen Plugins, die eine eigene Sektion ausgeben
if cd $PLUGINSDIR
then
  for skript in $(ls)
  do
    if [ -x "$skript" ] ; then
        ./$skript
    fi
  done
fi

# Lokale Einzelchecks
echo '<<<local>>>'
if cd $LOCALDIR
then
  for skript in $(ls)
  do
    if [ -x "$skript" ] ; then
        ./$skript
    fi
  done
fi

# MK's Remote Plugin Executor
if [ -e "$MK_CONFDIR/mrpe.cfg" ]
then
    echo '<<<mrpe>>>'
    grep -Ev '^[[:space:]]*($|#)' "$MK_CONFDIR/mrpe.cfg" | \
    while read descr cmdline
    do
        PLUGIN=${cmdline%% *}
        OUTPUT=$(eval "$cmdline")
        echo -n "(${PLUGIN##*/}) $descr $? $OUTPUT" | tr \\n \\1
        echo
    done
fi
