#!/bin/bash -e

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

pkgname=nagios-4.5.14

echo "INSTALL: Nagios Core is being installed..."

# Delete the old directory
rm -rf nagios
rm -rf "$pkgname"

# Extract archive
tar -xzf "$pkgname.tar.gz"
ln -s nagios "$pkgname"

# Apply our patches
echo "INSTALL: Applying Nagios XI patches to Nagios Core..."
./apply-patches "$pkgname" 

# Make and install Nagios
(
	cd "./$pkgname"
	configureflags="--with-command-group=$nagioscmdgroup"

	# use sysv (not upstart) if not systemd
	if [ ! `command -v systemctl` ]; then
		configureflags="--with-init-type=sysv $configureflags"
	fi

	# update default-service.in with proper After= section
    my="mysqld"
    if [ -f /usr/lib/systemd/system/mariadb.service ]; then
        my="mariadb"
    elif [ -f /usr/lib/systemd/system/mysql.service ] || [ -f /lib/systemd/system/mysql.service ]; then
        my="mysql"
    fi
    sed -i "s/local-fs.target/network-online.target local-fs.target $my.service/" startup/default-service.in

	./configure "$configureflags" 

	make -j $make_j_flag all  

	make install 
	make install-daemoninit 
	make install-commandmode 
)

# Post-install modifications
./post-install 

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

# Things are okay
echo "INSTALL: Nagios Core installed OK."
