#!/bin/bash
# Build and install script for check_throughput plugin
# Requires nagios-plugins to already be built (nagiosplugins subcomponent runs first).

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

if [ -f "${SCRIPT_DIR}/../../xi-sys.cfg" ]; then
    . "${SCRIPT_DIR}/../../xi-sys.cfg"
elif [ -f /usr/local/nagiosxi/var/xi-sys.cfg ]; then
    . /usr/local/nagiosxi/var/xi-sys.cfg
else
    echo "ERROR: Could not find xi-sys.cfg"
    exit 1
fi

WIZARD_PLUGINS_DIR="${SCRIPT_DIR}/../../nagiosxi/basedir/html/includes/configwizards/networkswitchrouter/plugins"
SOURCE_FILE="${SCRIPT_DIR}/check_throughput.c"
NAGIOS_PLUGINS_DIR=$(ls -d "${SCRIPT_DIR}/../nagiosplugins/nagios-plugins-2."* 2>/dev/null | head -1)
if [ -z "$NAGIOS_PLUGINS_DIR" ]; then
    echo "ERROR: Could not find nagios-plugins source directory"
    exit 1
fi
BUILD_DIR="${NAGIOS_PLUGINS_DIR}/plugins"
DEST_DIR="/usr/local/nagios/libexec"

echo "Building check_throughput plugin..."

# Ensure sqlite3 development headers are available (needed for -lsqlite3).
if [ "$distro" = "Ubuntu" ] || [ "$distro" = "Debian" ]; then
    if ! dpkg -s libsqlite3-dev >/dev/null 2>&1; then
        echo "Installing libsqlite3-dev..."
        apt-get install -y libsqlite3-dev
    fi
else
    if ! rpm -q sqlite-devel >/dev/null 2>&1; then
        echo "Installing sqlite-devel..."
        dnf install -y sqlite-devel 2>/dev/null || yum install -y sqlite-devel
    fi
fi

# nagios-plugins (nagiosplugins subcomponent) must be built before extraplugins
if [ ! -f "${BUILD_DIR}/utils.o" ]; then
    echo "Error: nagios-plugins build artifacts not found at ${BUILD_DIR}"
    echo "Ensure the nagiosplugins subcomponent has been built before extraplugins."
    exit 1
fi

cp "$SOURCE_FILE" "${BUILD_DIR}/"

if [ ! -f "${BUILD_DIR}/config.h" ]; then
    cp "${NAGIOS_PLUGINS_DIR}/config.h" "${BUILD_DIR}/"
fi

cd "${BUILD_DIR}"
NP_VERSION=$(basename "${NAGIOS_PLUGINS_DIR}" | sed 's/nagios-plugins-//')
NETSNMP_CFLAGS=$(net-snmp-config --cflags 2>/dev/null || echo "")
NETSNMP_LIBS=$(net-snmp-config --libs 2>/dev/null | sed 's/-specs=[^ ]*//g' || echo "-lnetsnmp")

gcc -DNP_VERSION="\"${NP_VERSION}\"" \
    -DLOCALEDIR=\"/usr/local/nagios/share/locale\" \
    -g -O2 -no-pie -I. -I../lib -I../gl ${NETSNMP_CFLAGS} \
    -o check_throughput check_throughput.c utils.o \
    ../lib/libnagiosplug.a ../gl/libgnu.a \
    -lm -ldl -lpthread -lcrypto -lsqlite3 ${NETSNMP_LIBS} 2>&1 | grep -v "deprecated" || true

if [ -f check_throughput ]; then
    echo "Build successful: check_throughput"

    echo "Installing check_throughput to ${DEST_DIR}..."
    cp check_throughput "${DEST_DIR}/"
    chown $apacheuser:$nagiosgroup "${DEST_DIR}/check_throughput"
    chmod ug+rwx "${DEST_DIR}/check_throughput"

    if [ -d "${WIZARD_PLUGINS_DIR}" ]; then
        cp check_throughput "${WIZARD_PLUGINS_DIR}/"
    fi

    echo "Installation complete: check_throughput installed successfully"
else
    echo "Build failed"
    exit 1
fi
