#!/bin/bash
set -e

NAGIOS_VERSION="4.5.11"
TARBALL="nagios-${NAGIOS_VERSION}.tar.gz"
DOWNLOAD_URL="https://github.com/NagiosEnterprises/nagioscore/releases/download/nagios-${NAGIOS_VERSION}/${TARBALL}"
SRCDIR="nagios-${NAGIOS_VERSION}"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
MODULE_DIR="$SCRIPT_DIR/module"

echo "==> Downloading Nagios Core ${NAGIOS_VERSION}..."
cd "$SCRIPT_DIR"
curl -fSL -o "$TARBALL" "$DOWNLOAD_URL"

echo "==> Extracting ${TARBALL}..."
tar xzf "$TARBALL"

echo "==> Running ./configure in ${SRCDIR}..."
cd "$SRCDIR"
./configure

if [ ! -d "$MODULE_DIR/include" ]; then
	echo "==> Creating $MODULE_DIR/include/..."
	mkdir -p "$MODULE_DIR/include"
fi
if [ ! -d "$MODULE_DIR/lib" ]; then
	echo "==> Creating $MODULE_DIR/lib/..."
	mkdir -p "$MODULE_DIR/lib"
fi

echo "==> Copying header files to module include/ and lib/ directories..."
cp -v include/*.h "$MODULE_DIR/include/"
cp -v lib/*.h "$MODULE_DIR/lib/"

echo "==> Headers installed into:"
echo "      $MODULE_DIR/include/"
echo "      $MODULE_DIR/lib/"

echo "==> Building module..."
cd "$MODULE_DIR"
make clean
make

echo "==> Stopping Nagios..."
sudo systemctl stop nagios

echo "==> Installing module..."
sudo make install

echo "==> Starting Nagios..."
sudo systemctl start nagios

NAGIOS_CFG="/usr/local/nagios/etc/nagios.cfg"
BROKER_LINE="broker_module=/usr/local/nagios/bin/influx_perf_api_v1.o http://localhost:8086/write?db=perfdata timeout=10 batch=10"

echo "==> Checking broker_module directive in ${NAGIOS_CFG}..."
if grep -qF "broker_module=/usr/local/nagios/bin/influx_perf_api_v1.o" "$NAGIOS_CFG"; then
	echo "    broker_module directive found."
else
	echo 
	echo "    WARNING: broker_module directive not found in ${NAGIOS_CFG}"
	echo "    You need to add the following line to ${NAGIOS_CFG}:"
	echo "    ${BROKER_LINE}" 
	echo 
fi

echo "==> Done. Module built and installed."
