#!/bin/bash -e

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

pkgname="nrpe-4.1.3"

echo "INSTALL: NRPE is being installed..."

# Delete the old archive
rm -rf "$pkgname"

# Extract archive
tar -xzf "$pkgname.tar.gz"

# Make and install 
(
	cd "./$pkgname"
	if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
		./configure --with-ssl=/usr/bin/openssl --with-ssl-lib=/usr/lib/x86_64-linux-gnu --enable-command-args   
	elif [ "$distro" == "Raspbian" ]; then
		./configure --with-ssl-lib=/usr/lib/arm-linux-gnueabihf --libexecdir=/usr/local/nagios/libexec --enable-command-args 
	else
		./configure --enable-command-args 
	fi

	# Temp fix for SSL issues with nrpe
	if [ "$dist" == "el8" ] || [ "$dist" == "el9" ] || [ "$dist" == "debian11" ] || [ "$dist" == "ubuntu22" ] || [ "$dist" == "ubuntu24" ]; then
		sed -i "s/#define USE_SSL_DH 1/#undef USE_SSL_DH/" include/config.h
	fi

	make -j $make_j_flag all 
	make install-plugin 
	make install-daemon  
	make install-config  
	make install-init 
)

# Configure NRPE for client use (allow remote monitoring and argument passing)

NRPECFG=/usr/local/nagios/etc/nrpe.cfg

# Add dont_blame_nrpe=1 to the config file to allow argument passing
sed -i 's/^dont_blame_nrpe=0/dont_blame_nrpe=1/' "$NRPECFG"

# Comment out the default check_users / check_load lines that use hardcoded thresholds
sed -i -E 's|^command\[check_users\]=.*-w 5 -c 10.*$|#&|' "$NRPECFG"
sed -i -E 's|^command\[check_load\]=.*-r -w .*$|#&|' "$NRPECFG"

# Uncomment the XI-style command definitions that ship commented out in nrpe.cfg.
for cmd in check_users check_load check_disk check_swap check_cpu_stats check_mem \
			check_init_service check_services check_yum check_apt check_all_procs \
			check_procs check_open_files check_netstat; do
	sed -i -E "s|^#(command\[${cmd}\]=)|\1|" "$NRPECFG"
done

# Strip sudo out of the check_init_service command
sed -i -E 's|^(command\[check_init_service\]=)sudo +|\1|' "$NRPECFG"

# check_ide_smart is not in the default nrpe.cfg - append it if missing.
if ! grep -q '^command\[check_ide_smart\]' "$NRPECFG"; then
	echo 'command[check_ide_smart]=/usr/local/nagios/libexec/check_ide_smart $ARG1$' >> "$NRPECFG"
fi


# Start NRPE
if [ ! `command -v systemctl` ]; then
	service nrpe start
else
	systemctl daemon-reload 
	systemctl start nrpe 
fi

# Do a simple sanity check to make sure some key files exist...
for f in /usr/local/nagios/bin/nrpe /usr/local/nagios/libexec/check_nrpe ; do
	if [ ! -f "$f" ]; then
		echo "ERROR: NRPE install appears to have failed - exiting.  Missing file = $f"
		exit 1
	fi
done

# Things are okay
echo "INSTALL: NRPE installed OK."

