#!/bin/bash -e

# Create a unique working directory
workdir="/usr/local/nagiosxi/tmp/ndo-$(date +%s)"

if [ -d "$workdir" ]; then
	echo "ERROR: Directory $workdir already exists."
	exit 1
fi

mkdir -p "$workdir"
cd "$workdir"

# Extract the ndo-3.1.1 tarball
if [ ! -f /usr/local/nagiosxi/tmp/ndo-3.1.1.tar.gz ]; then
	echo "ndo-3.1.1.tar.gz not found, attempting to download from assets.nagios.com..."

	if ! wget -O xi-latest.tar.gz --timeout=120 http://assets.nagios.com/downloads/nagiosxi/xi-latest.tar.gz; then
		echo "ERROR: Failed to download xi-latest.tar.gz."
		exit 1
	fi

	if ! tar -xzvf xi-latest.tar.gz --wildcards "*ndo-3.1.1.tar.gz" --transform='s|.*/||'; then
		echo "ERROR: Failed to extract ndo-3.1.1.tar.gz from xi-latest.tar.gz."
		exit 1
	fi

	if [ ! -f ndo-3.1.1.tar.gz ]; then
		echo "ERROR: ndo-3.1.1.tar.gz not found after extraction."
		exit 1
	fi
fi

tar -xzf /usr/local/nagiosxi/tmp/ndo-3.1.1.tar.gz

# Compile NDO
cd ndo-3.1.1
./configure
make all

# Stop Nagios, install NDO, and restart Nagios
systemctl stop nagios
make install
systemctl start nagios

echo "NDO 3.1.1 has been installed successfully."
