#!/bin/sh
# Copyright (C) 2026 Christian Wirtz <doc@snowheaven.de>
# License: GPL-2.0-only, see LICENSE in the repository root.
#
# Checkmk agent plug-in: port_connections
#
# Emits the <<<port_connections>>> section with one socket per line in an
# unambiguous format:
#
#     <proto> <state> <local_address> <remote_address>
#
# e.g.
#
#     tcp ESTAB 192.168.1.21:80 192.168.1.5:43630
#     udp UNCONN 0.0.0.0:514 0.0.0.0:*
#
# This section is the only data source of the "port_connections" check
# plug-in (MKP). Unlike the generic <<<netstat>>> section it is not affected
# by the netstat-vs-ss column order ambiguity, so connection states are
# always preserved.
#
# Installation: copy this file to the agent plug-in directory of the
# monitored host (usually /usr/lib/check_mk_agent/plugins/) and make it
# executable, or deploy it via the agent bakery rule
# "Port connections agent".

CMK_VERSION="2.2.3"

if command -v ss >/dev/null 2>&1; then
    echo "<<<port_connections>>>"
    ss -tuan 2>/dev/null | awk '($1 == "tcp" || $1 == "udp") { print $1, $2, $5, $6 }'
elif command -v netstat >/dev/null 2>&1; then
    echo "<<<port_connections>>>"
    netstat -tuan 2>/dev/null | awk '$1 ~ /^(tcp|udp)/ { state = (NF >= 6) ? $6 : "UNCONN"; print $1, state, $4, $5 }'
fi

exit 0
