#!/bin/bash -e

. ../../xi-sys.cfg

destdir=/usr/local/nagios/libexec

echo "UPGRADE: Extra Plugins are being upgraded..."

cp -r plugins/* "$destdir"
cp -r proy_plugins/*.pl "$destdir"
cp -r rrdtraf-v0.1/check_rrdtraf-v0.1.php "$destdir/check_rrdtraf.php"
cp -r check_rrdtraf-0.5/check_rrdtraf "$destdir"
cp -r check_postgres-2.26.0/check_postgres.pl "$destdir"

# Do the check_mysql_health magic
(
	cd ./check_mysql_health-2.1.8.2
	./configure # Have to configure to make makefile to make clean. arg.
	make clean
	./configure
	make
)

# Install Nagios::Monitoring::Plugin
(
   tar xzf Nagios-Monitoring-Plugin-0.51.tar.gz
   cd Nagios-Monitoring-Plugin-0.51
   perl Makefile.PL
   make
   make test
   make install
)

cp -r check_mysql_health-2.1.8.2/plugins-scripts/check_mysql_health "$destdir"

# Ensure net-snmp development headers are available (needed by check_throughput and check_snmp_interface_status)
if [ "$distro" = "Ubuntu" ] || [ "$distro" = "Debian" ]; then
    if ! dpkg -s libsnmp-dev >/dev/null 2>&1; then
        echo "Installing libsnmp-dev..."
        apt-get install -y libsnmp-dev
    fi
else
    if ! rpm -q net-snmp-devel >/dev/null 2>&1; then
        echo "Installing net-snmp-devel..."
        dnf install -y net-snmp-devel 2>/dev/null || yum install -y net-snmp-devel
    fi
fi

# Build and install check_throughput plugin
echo "Building and installing check_throughput plugin..."
bash ./build_check_throughput.sh

# Build and install check_snmp_interface_status plugin
echo "Building and installing check_snmp_interface_status plugin..."
(
    cd ./check_snmp_interface_status
    make clean || true
    make
    cp check_snmp_interface_status "$destdir"
)

# Ensure the sudoers entry for seed_throughput_db.php exists.
if ! grep -q 'seed_throughput_db.php' /etc/sudoers /etc/sudoers.d/* 2>/dev/null; then
    echo "NAGIOSXIWEB ALL = NOPASSWD:/usr/bin/php /usr/local/nagiosxi/scripts/seed_throughput_db.php *" >> /etc/sudoers
fi

echo "UPGRADE: Extra Plugins upgraded OK."
