#!/bin/sh

# Copyright 2015-2022 Rivoreo

# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

if [ -z "${PROGRAM_DIR+set}" ]; then
	echo "You should not run this script directly" 1>&2
	exit 255
fi

count_lines() {
	[ -f "$LINPROCFS/net/$1" ] && value=`wc -l < "$LINPROCFS/net/$1"` || return
	value=$((value-1))
	influxdb_values="$influxdb_values,n${2}sockets=$value"
	if [ -n "$CARBON_SERVER" ]; then
		printf %s\\n "sockstat.$HOSTNAME_FOR_CARBON.n${2}sockets $value -1"
	fi
}

[ -n "$LINPROCFS" ] && [ -f "$LINPROCFS/net/sockstat" ] || LINPROCFS=/proc
while true; do
	influxdb_values=
	if [ -f "$LINPROCFS/net/sockstat" ] && exec 3< "$LINPROCFS/net/sockstat"; then
		while read line; do case "$line" in
			"sockets: used "*)
				value="${line#sockets: used }"
				[ "$value" -ge 0 ] || continue
				influxdb_values="$influxdb_values,nsockets=$value"
				if [ -n "$CARBON_SERVER" ]; then
					printf %s\\n "sockstat.$HOSTNAME_FOR_CARBON.nsockets $value -1"
				fi
				;;
			[A-Z]*": "*)
			#[TUR]*": "*)
				protocol="`printf %s \"${line%%:*}\" | sed y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/`"
				key=
				for i in ${line#*: }; do if [ -n "$key" ]; then
					influxdb_values="$influxdb_values,$key=$i"
					if [ -n "$CARBON_SERVER" ]; then
						printf %s\\n "sockstat.$HOSTNAME_FOR_CARBON.$key $i -1"
					fi
					key=
				else
					key="${protocol}_${i}"
				fi done
				;;
		esac done 0<&3
		exec 3<&-
	else
		for t in tcp udp raw unix; do count_lines $t $t; done
	fi
	[ -f "$LINPROCFS/net/sctp/assocs" ] && count_lines sctp/assocs sctp
	if [ -n "$INFLUXDB_BASE_URL" ] && [ -n "$influxdb_values" ]; then
		http_post "${INFLUXDB_BASE_URL}write?db=$INFLUXDB_DB_NAME" \
			"sockstat,host=$HOSTNAME ${influxdb_values#,}" 1>&2
	fi
	sleep "$INTERVAL"
done | send_carbon_lines
