#!/bin/sh
############################################################ IDENT(1)
#
# $Title: Script to launch telegraf to send JSON log to InfluxDB $
# $Copyright: 2022 Devin Teske. All rights reserved. $
# $FrauBSD$
#
############################################################ INFORMATION
#
# See CONF file for setting which JSON log gets processed, which database host
# to send the data to (does not necessarily have to be InfluxDB), and how to
# treat the JSON data that is to be sent.
#
############################################################ PROGRAM

pgm="${0##*/}" # Program basename
_pgm="${pgm%_*}" # Program suite

############################################################ CONFIGURATION

CONF="$_pgm/stats.conf"
LOGFILE="/var/log/$_pgm/stats.log"
ERRLOGFILE="/var/run/$_pgm/stats.stderr"
PIDFILE="/var/run/$_pgm/stats.pid"

############################################################ ENVIRONMENT

#
# Adjust PATH
# NB: So we can find telegraf in MAIN
#
if ! type telegraf > /dev/null 2>&1; then
	for dir in \
		/usr/local/bin \
	; do
		[ -e "$dir/telegraf" ] || continue
		PATH="$PATH${PATH:+:}$dir"
	done
	# ... otherwise let the error come through
fi

############################################################ GLOBALS

#
# Global exit status
#
SUCCESS=0
FAILURE=1

#
# OS Glue
#
CONFDIR=/etc
case "${UNAME_s:=$( uname -s )}" in
FreeBSD) CONFDIR=/usr/local/etc ;;
esac

############################################################ FUNCTIONS

usage()
{
	echo "Usage: $pgm" >&2
	exit $FAILURE
}

############################################################ MAIN

[ $# -eq 0 ] || usage # NOTREACHED

#
# Launch telegraf to send file to influxdb
#
telegraf --config "$CONFDIR/$CONF" >> "$LOGFILE" 2>> "$ERRLOGFILE" &

#
# Create pid file
#
pid=$!
echo $pid > "$PIDFILE"

#
# Yield time so telegraf has time to parse the config file for syntax errors
#
sleep 0.25

#
# Generate exit status
#
kill -0 $pid

################################################################################
# END
################################################################################
