#!/bin/bash -e

if [ $UID != 0 ] ; then
        printf "\n\n ***************************************\n You must run the upgrade script as root\n ***************************************\n\n\n\a"
	exit 1
fi


# Add variables from pre existing xivar
if [ -f "/usr/local/nagiosxi/var/xi-sys.cfg" ]; then
	cp -f /usr/local/nagiosxi/var/xi-sys.cfg ./xi-sys.cfg
fi

# Set up system variables
./init.sh
. ./xi-sys.cfg
. ./functions.sh

# Prevent PHP's SNMP extension from loading all MIBs during upgrade.
export MIBS=""

# Ensure these passwords are also in xi-sys.cfg
./xivar nagiosxipass "$cfg__db_info__nagiosxi__pwd"
./xivar nagiosqlpass "$cfg__db_info__nagiosql__pwd"
./xivar ndoutilspass "$cfg__db_info__ndoutils__pwd"
# No dbmaint password yet
if [ -z "$cfg__db_info__nagiosxi__dbmaint_pwd" ]; then
	dbmaintpass="$(tr -dc '[:alnum:]' < /dev/urandom | head -c 20)"
	./xivar dbmaintpass "$dbmaintpass"
else
	./xivar dbmaintpass "$cfg__db_info__nagiosxi__dbmaint_pwd"
fi

# Explicitly set umask
umask 0022

BASEDIR=$(dirname "$0")

# Set up XI config dbservers with non-standard ports
if [ "$cfg__db_info__nagiosxi__dbserver" != "x$cfg__db_info__nagiosxi__dbserver" ]; then
	cfg__db_info__nagiosxi__dbserver="${cfg__db_info__nagiosxi__dbserver/:/ -P }"
fi
if [ "$cfg__db_info__nagiosql__dbserver" != "x$cfg__db_info__nagiosql__dbserver" ]; then
	cfg__db_info__nagiosql__dbserver="${cfg__db_info__nagiosql__dbserver/:/ -P }"
fi
if [ "$cfg__db_info__ndoutils__dbserver" != "x$cfg__db_info__ndoutils__dbserver" ]; then
	cfg__db_info__ndoutils__dbserver="${cfg__db_info__ndoutils__dbserver/:/ -P }"
fi

# Subcomponents that may need to be recompiled, flags set so it's only done once per upgrade
UPDATE_CORE=0
UPDATE_NDO=1
UPDATE_MRTG=0
UPDATE_PNP=0
UPDATE_PLUGINS=1
UPDATE_NRPE=0
UPDATE_NSCA=0
UPDATE_NRDP=0
UPDATE_ADDONS=0
UPDATE_SUDOERS=0
UPDATE_PHANTOMJS=0
UPDATE_LOGROTATE=0

export INSTALL_PATH=`pwd`
if [ "x$INTERACTIVE" = "x" ]; then
    export INTERACTIVE="True"
fi
if [ "x$FORCE_ADDON_UPGRADE" = "x" ]; then
    export FORCE_ADDON_UPGRADE=0
fi

# Get the current version of XI
oldversion=$(./get-version)

# Get the new version of XI
. "./nagiosxi/basedir/var/xiversion"
newversion=$release

if [ "$oldversion" -eq 0 ]; then
	echo "ERROR: Could not determine currently installed version of Nagios XI!" 
	exit 1
fi

if [ "$newversion" -lt "$oldversion" ]; then
	echo "ERROR: Can not downgrade Nagios XI!"
	exit 1
fi

# Parse command line
while [ -n "$1" ]; do
	case "$1" in
		-h | --help)
			usage_upgrade
			exit 0
			;;
		-v | --version)
			echo "${oldversion}"
			exit 0
			;;
		-n | --non-interactive)
			export INTERACTIVE="False"
			;;
		-p | --mysql-password)
			mysqlpass="$2"
			./xivar mysqlpass "$2"
			shift
			;;
		-o | --offline-install)
			echo "Offline installs now use RPMs. Upgrade instructions are at: https://assets.nagios.com/downloads/nagiosxi/docs/Installing-Nagios-XI-2024-Offline.pdf"
			exit 0
			;;
	    -f | --force)
			export FORCE=1
			;;
		*)
			echo "Unknown option:  $1" 
			usage_upgrade 
			exit 1
	esac
	shift
done

if [ "$oldversion" -lt 60000 ]; then
	printf "\n--------------------------------------\nYour version of XI is too old:\n--------------------------------------\nIt appears that you currently are using a version of XI that is more than two years old.  You will need to upgrade to a 2024 version of XI greater than 2024R1 before upgrading to this version.  You can find previous versions of XI at our archive site:\n\nhttps://assets.nagios.com/downloads/nagiosxi/versions.php \n\n\nIf you need assistance with the upgrade process feel free to open a support case by visiting our Customer Support Portal:\n\nhttps://support.nagios.com \n\nIf you are unable to access our Customer Support Portal please contact your Customer Success Manager for further assistance (csm@nagios.com).\n\n\n" 
	exit 1 ; 
fi


# As of XI 2024R1, there will be no more PostgresQL support!!!

if [ "$cfg__db_info__nagiosxi__dbtype" == "pgsql" ]; then
	echo "-------------------------------"
	echo " Removal of PostgreSQL Support "
	echo "-------------------------------"
	echo ""
	echo "Nagios XI no longer supports PostgreSQL."
	echo "To upgrade to this version of Nagios XI, please migrate your database to use MySQL or MariaDB, "
	echo "preferably the version supported by your Linux distribution. As part of migrating the database "
	echo "to upgrade to this Nagios XI version, we recommend upgrading first to Nagios XI version 5.11.3. "
	echo "Then either open a ticket with Nagios support (support@nagios.com) or run the script at "
	echo "pg2mysql/convert_nagiosxi_to_mysql.php. "
	echo ""
	echo "For more information, please visit the support forum:"
	echo "https://support.nagios.com/forum/"
	echo ""
	exit 1
fi

# Stop if it is not a supported distro
case "$dist" in
    el8 )
        if [ "$distro" == "CentOS" ]; then
            echo "CentOS Stream 8 is no longer supported due to end of life."
            exit 1
        fi
        :
        ;;
    el9 )
        :
        ;;
    ubuntu22 | ubuntu24 )
        :
        ;;
    debian12 )
        :
        ;;
    el5 | el6 | el7 | ubuntu14 | ubuntu16 | ubuntu18 | ubuntu20 | debian8 | debian9 )
		echo "------------------------------" 
		echo " Distro End of Life" 
		echo "------------------------------" 
		echo "" 
		echo "Nagios XI ${xiver} does not support $distro $version due to EOL." 
		echo "To upgrade to Nagios XI ${xiver}, please use one of the following distros:" 
        echo "  CentOS Stream 9, RHEL or Oracle 8, 9" 
        echo "  Ubuntu 22.04 LTS, or 24.04 LTS" 
        echo "  Debian 12" 
		echo "" 
		echo "For more information on how to transition, please visit the support forum:" 
		echo "https://support.nagios.com/forum/" 
        exit 1
        ;;
    *)
        echo "$distro $version is not currently supported. Please use one of the following distros:" 
        echo "  CentOS Stream 9, RHEL or Oracle 8, 9" 
        echo "  Ubuntu 22.04 LTS, or 24.04 LTS" 
        echo "  Debian 12" 
        exit 1
esac


if [ "$distro" != "Ubuntu" ] && [ "$distro" != "Debian" ]; then

    if rpm -q nagiosxi >/dev/null; then
        echo "RPM Install detected, switching to yum update"
        if [ "$INTERACTIVE" = "True" ]; then
            yum update nagiosxi
            exit $?
        else
            yum update nagiosxi -y
            exit $?
        fi
    fi
fi

# Restart the upgrade
if [ -t 1 ]; then
	"$0" 2>&1 | tee -a "upgrade.log"

	exit 0
fi

# Check to make sure we aren't running a normal upgrade on an RPM/offline install
echo "Checking install type..."
if command -v "rpm" &> /dev/null && rpm -q nagiosxi &> /dev/null; then
	if dnf repolist | grep -q "nagios"; then
		echo "rpm" > /usr/local/nagiosxi/var/xi-itype
	else
		echo "offline" > /usr/local/nagiosxi/var/xi-itype
	fi
else
	# Whenever we get a way to differentiate source and ova, then put that check here
	echo "source" > /usr/local/nagiosxi/var/xi-itype
fi
installtype=$(</usr/local/nagiosxi/var/xi-itype)
echo "Install type: $installtype"

if [ "$installtype" = "offline" ]; then
	echo "======================================================================"
	echo "ERROR: Offline installation detected!"
	echo "You are attempting to upgrade using the source/tarball upgrade script."
	echo "======================================================================"
	echo ""
	echo "Please follow the offline upgrade process."
	echo "For more information, refer to the following documentation:"
	echo "https://nagiosenterprises.my.site.com/support/s/article/Installing-Nagios-XI-in-an-Offline-Environment-5423fcb3"
	echo ""
	exit 1
fi
if  [ "$installtype" = "rpm" ]; then
	echo "======================================================================"
	echo "ERROR: RPM installation detected!"
	echo "You are attempting to upgrade using the source/tarball upgrade script."
	echo "======================================================================"
	echo ""
	echo "Please follow the RPM upgrade process."
	echo "For more information, refer to the following documentation:"
	echo "https://repo.nagios.com/?repo=rpm-rhel"
	echo ""
	exit 1
fi
if [ "$installtype" = "ova/vhd" ]; then
    echo "==============================================================="
	echo "WARNING: OVA/VHD installation detected!"
	echo "==============================================================="
    echo ""
	echo "DANGER: OVA/VHD images are intented for evaluation, not production use and maintenance."
    echo ""
	echo "We provide our OVA images as a convenience and they are not indented for production use. The virtual"
	echo "machine images are not considered official distributions and only the Nagios Software contained within the"
	echo "image is an official distribution. We provide them to enable our customers to quickly bootstrap and evaluate"
	echo "our product. They are provided “as is” without warranty of any kind and we do not manage and/or maintain the"
	echo "image after creation. You are welcome to use our OVA in production if you like however we do not support the"
	echo "operating system nor any alterations to the underlying dependencies/components. If you want to upgrade the"
	echo "version of Nagios XI on one of our images you want to follow our normal instructions for upgrading Nagios XI: "
    echo ""
	echo "https://assets.nagios.com/downloads/nagiosxi/docs/XI-Upgrade-Instructions.pdf"
    echo ""

	if [ "$INTERACTIVE" = "True" ]; then
		read -p "Are you sure you want to continue? [y/N] " res

		if [ "$res" = "y" -o "$res" = "Y" ]; then
			echo "Proceeding with upgrade..."
		else
			echo "Upgrade cancelled"
			exit 0
		fi
	fi

fi

echo ""
echo "Installation check passed."

# Do a verification check that they want to proceed
if [ "$INTERACTIVE" = "True" ]; then

	fmt -s -w $(tput cols) <<-EOF

		IMPORTANT: Before upgrading, verify you have both a valid system backup as well as a configuration backup of Nagios XI before continuing! More information about backing up and restoring Nagios XI can be found here:  https://assets.nagios.com/downloads/nagiosxi/docs/Backing-Up-and-Restoring-Nagios-XI-2024.pdf
		
		NOTICE: Your Nagios XI license includes a test environment instance that allows you to verify successful upgrade and configuration changes before applying them to your production environment. As a best practice for ensuring the reliability of your monitoring systems, we advise you to upgrade your test environment before upgrading any production instances. More information on licensing can be found here: https://assets.nagios.com/downloads/nagiosxi/docs/Nagios-XI-License-Information.pdf
	
	EOF

	read -p "Are you sure you want to continue? [y/N] " res

	if [ "$res" = "y" -o "$res" = "Y" ]; then
		echo "Proceeding with upgrade..."
	else
		echo "Upgrade cancelled"
		exit 0
	fi

fi

# Initialize install.log
echo "Nagios XI Upgrade Log
==========================
DATE: $(date)

DISTRO INFO:
$distro
$version
$architecture

"

# Remove debian chromium. Prereqs takes care of conflict with mysql headers. We will add back later
if [ "$distro" == "Ubuntu" ]; then
	if [ -e /etc/apt/preferences.d/chromium.pref ]; then
		# Remove possible files
		rm -f /etc/apt/preferences.d/chromium.pref
		if [ -e /etc/apt/sources.list.d/debian.list ]; then
			rm -f /etc/apt/sources.list.d/debian.list
		fi
		if [ -e /etc/apt/sources.list.d/zzz_debian.list ]; then
			rm -f /etc/apt/sources.list.d/zzz_debian.list
		fi
		if [ -h /bin/chromium-browser ]; then
			rm -f /bin/chromium-browser
		fi

		# Actually remove
		apt remove -y chromium
		apt autoremove -y
		apt update

		if [ "$dist" == "ubuntu22" ]; then
			apt install -y --allow-downgrades libzstd1/jammy libmysqlclient-dev
		elif [ "$dist" == "ubuntu24" ]; then
			apt install -y --allow-downgrades libzstd1/noble libmysqlclient-dev
		fi
	fi
fi

# Copy xi-sys.cfg
cp xi-sys.cfg "$proddir/var/"
cp xi-sys.cfg ./nagiosxi/basedir/var/

# Make a copy of xi-sys.cfg to store in etc for strict permissions
cp xi-sys.cfg "$proddir/etc/"
cp xi-sys.cfg ./nagiosxi/basedir/etc/
chown root.$nagiosgroup "$proddir/etc/xi-sys.cfg"
chown root.$nagiosgroup ./nagiosxi/basedir/etc/xi-sys.cfg
chmod 550 "$proddir/etc/xi-sys.cfg"
chmod 550 ./nagiosxi/basedir/etc/xi-sys.cfg

# Set up directory for keys and XI server's encryption key (make one if
# one doesn't already exist ... XI < 5.5)
if [ ! -f $proddir/var/keys/xi.key ]; then
	mkdir -p $proddir/var/keys
	openssl rand -hex 16 > $proddir/var/keys/xi.key
fi
chown $nagiosuser:$nagiosgroup $proddir/var/keys/xi.key
chmod 640 $proddir/var/keys/xi.key

# Install Sourceguardian extension
./install-sourceguardian-extension.sh
./nagiosxi/basedir/scripts/manage_services.sh restart httpd

# Verify server has needed prereqs
/usr/bin/php ./verify-prereqs.php

# Get existing version ID
# oldversion=$(./get-version)


echo "OLD VERSION: $oldversion"
echo "NEW VERSION: $newversion"

####################### "Preflight" Checking #################

# Are there unapplied Core configuration changes?
if [ "$cfg__db_info__nagiosxi__dbserver" == "" ]; then
    cfg__db_info__nagiosxi__dbserver="localhost";
fi

apply_config_needed=$(mysql -h $cfg__db_info__nagiosxi__dbserver -u $cfg__db_info__nagiosxi__user --password="$cfg__db_info__nagiosxi__pwd" --database=$cfg__db_info__nagiosxi__db -B -N -e "SELECT value FROM xi_options WHERE name = 'ccm_apply_config_needed'")
if [ $apply_config_needed -eq 1 ]; then
	echo "The Core Configuration Manager has unapplied changes."
	echo "Please apply or discard your changes before upgrading Nagios XI."
	exit 1
fi

# Do the current config files allow a successful restart?
/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
if [ $? -ne 0 ]; then
	echo "Nagios Core has one or more problems that may prevent it from restarting."
	echo "Please address any configuration issues before upgrading Nagios XI."
	exit 1
fi

##########################################
# UPDATE THIS VERSION IF YOU UPDATE CORE #
##########################################
if [ "$oldversion" -lt 80700 ]; then
	echo "Checking if any NEB Modules are installed besides NDO and Nagios Mod-Gearman"
	if grep "^broker_module" /usr/local/nagios/etc/nagios.cfg | awk '!/(ndo|nagios-mod-gearman|influx_perf_api)/' | grep -q '.'; then
		message="Non-standard NEB modules detected while attempting to upgrade. You will need to upgrade the associated NEB modules manually before proceeding with the upgrade."
		echo ""
		echo "$message"
		echo "This link will provide more information: https://support.nagios.com/kb/article/upgrade-error-with-xi-and-non-standard-broker-modules-1047.html#:~:text=When%20upgrading%20to%20the%20most,is%20part%20of%20Nagios%20XI."
		echo ""
		# Doing relative instead of $proddir because I don't think this will be added by the time we'd want to run this
		if [ $oldversion -gt 51100 ]; then
			/usr/bin/php ./nagiosxi/basedir/scripts/add_admin_banner.php -m "$message" -t "warn" &> /dev/null || true
		fi
		exit 1
	fi
fi

####################### DEPENDENCY INSTALLER #################

if [ `command -v yum` ]; then

	if rpm -q nagios-repo >/dev/null; then
		yum update nagios-repo -y
	fi

	if [ "$distro" == "CentOS" ] || [ "$distro" == "RedHatEnterpriseServer" ] || [ "$distro" == "OracleServer" ]; then

		if [ $ver -eq 9 ]; then
			xiverrpm="nagiosxi-deps-el9"
		elif [ $ver -eq 8 ]; then
			xiverrpm="nagiosxi-deps-el8"
		fi

		# Attempt to update dependencies, and if it fails for some reason clean the repos

		yumlocalinstall="$(readlink -e ./$xiverrpm-$xiver-1.noarch.rpm)"

		if ! yum -y --nogpgcheck localinstall $yumlocalinstall; then
			yum clean all
			yum -y --nogpgcheck localinstall $yumlocalinstall
		fi


		# RHEL 8/Oracle 8 need to use python3.9 for AWS Boto to work.  Setting with 'alternatives'.
		if [ $ver -eq 8 ]; then
			# Set 'alternatives' to python3.9
			# NOTE: we are installing python 3.9 (39), so make sure we link /usr/bin/python to 3.9.
			alternatives --set python3 /usr/bin/python3.9

			# Link python3 to python so we are using 3 normally
			if [ ! -f /usr/bin/python ]; then
					echo "### SETTING PYTHON LINK ###"
					ln -s /usr/bin/python3 /usr/bin/python
			fi

			# Ensure the correct rrdtool module version is installed:
			python3 -m pip install rrdtool
		fi
		if rpm -q $xiverrpm >/dev/null; then 
			printf "\n Dependancy RPM $xiverrpm installed. \n" 
		else
			printf "\n Warning Dependancy RPM $xiverrpm not installed. \n " 
			# Manually install the new php packages for systems without deps package (upgraded php versions)
			if [ "$ver" -le 8 ]; then
				yum install $(yum list installed php*common* | grep php | awk -F "-" '{print $1}' | tail -1)-imap -y
			fi
		fi
		# Remove existing Packages
		yum remove -y --noautoremove php-pecl-ssh2
		if [ "$oldversion" -lt 80700 ]; then
			# Handle libssh2 installation
			yum remove -y --noautoremove libssh2 libssh2-devel
			tar -zxvf nagiosxi/basedir/html/includes/components/scheduledbackups/includes/libssh2-1.10.0.tar.gz
			cd libssh2-1.10.0

			# Configure and install libssh2:
			./configure
			make
			make install
			cd ..
			# Install local pecl-ssh2 package
			pecl uninstall ssh2
			sed -i 's/^extension=ssh2\.so/;extension=ssh2.so/' /etc/php.d/*ssh2.ini
			pecl config-set php_ini "$(php -r 'echo php_ini_loaded_file();')" 2>/dev/null || true
			printf "\n" | pecl install nagiosxi/basedir/html/includes/components/scheduledbackups/includes/ssh2-1.4.1.tgz || pecl list | grep -qi ssh2
			echo "extension=ssh2.so" > /etc/php.d/ssh2.ini
		fi
	fi

else

	# Add dependencies on Ubuntu/Debian systems

	if [ "$oldversion" -lt 60200 ]; then
		apt-get install -y dos2unix
	fi

	if [ "$oldversion" -lt 60202 ] && [ "$dist" == "ubuntu24" ] ; then
		apt-get install -y tzdata-legacy
	fi

	if dpkg -l | grep -q "php.*-ssh2"; then
		
		# Removes php-ssh2 this includes php*-ssh2 
		apt remove --purge -y $(dpkg --get-selections | awk '{print $1}' | grep -E '^php[0-9-]+.*-ssh2$')
		printf "\n" | pecl install nagiosxi/basedir/html/includes/components/scheduledbackups/includes/ssh2-1.4.1.tgz || pecl list | grep -qi ssh2
		echo "extension=ssh2.so" | tee -a $(find /etc/php -name "php.ini" | grep apache2)
		echo "extension=ssh2.so" | tee -a $(find /etc/php -name "php.ini" | grep cli)
	fi
fi

####################### END OF DEPENDENCY INSTALLER #################

####################### VERSION-SPECIFIC FIXES ####################################



# Version < 6.00.00
if [ "$oldversion" -lt 60000 ]; then

	# Fix permissions for bpi.conf
	touch "$proddir/etc/components/bpi.conf"
	chown "$apacheuser:$nagiosgroup" "$proddir/etc/components/bpi.conf"
	chmod 664 "$proddir/etc/components/bpi.conf"

    # Do database updates
    if [ ! -f 'mysql.60000.updated' ]; then
        if [ "$cfg__db_info__nagiosxi__dbserver" == "" ]; then
            cfg__db_info__nagiosxi__dbserver="localhost";
        fi

        # Add wizard tracking table to database
		mysql -h $cfg__db_info__nagiosxi__dbserver -u $cfg__db_info__nagiosxi__user --password="$cfg__db_info__nagiosxi__pwd" --database=$cfg__db_info__nagiosxi__db --force < nagiosxi/nagiosxi-db/mods/mysql/schema_60000.sql
        touch 'mysql.60000.updated'
    fi
fi

# Fix for PhantomJS not installing/upgrading
if [ "$oldversion" -lt 60001 ]; then
	UPDATE_PHANTOMJS=1
fi

if [ "$oldversion" -lt 60002 ]; then
	# Update for security fixes
	UPDATE_CORE=1

	# Update automysqlbackup #247 DA
	if [ -f "/root/scripts/automysqlbackup" ]; then
		revision="\nif mysqldump --column-statistics=0 --version \&>\/dev\/null\; then\n\tOPT=\"--column-statistics=0 \$OPT\"\nfi"
		sed -i "s/$(grep '^OPT=' /root/scripts/automysqlbackup)/&\n$revision/" /root/scripts/automysqlbackup
	fi

	# This is the database we care about here. We need to make sure it's valid
	if [ "$cfg__db_info__nagiosxi__dbserver" == "" ]; then
		cfg__db_info__nagiosxi__dbserver="localhost";
	fi

	# Get root mysql password
	# Test for pre-saved password (from ./fullinstall script)
	if mysqlshow -h $cfg__db_info__nagiosxi__dbserver -u root -p"$mysqlpass" &>/dev/null; then
	    echo "Saved password worked..."
	    domysqlupdate="yes"
	else
	    for i in 1 2 3; do
	        if [ "$INTERACTIVE" = "True" ]; then
	            # Ask for the password
	            echo "Enter the MySQL root password to continue..."
	            read -p "MySQL Root Password: " pass
	        fi

	        # Test the password
	        if mysqlshow -h $cfg__db_info__nagiosxi__dbserver -u root -p"$pass" &>/dev/null; then
	            echo "Password validated."
	            domysqlupdate="yes"
	            mysqlpass="$pass"
	            break
	        else
	            echo "Password failed." 
	            if [ $i -eq 3 ]; then
	            	echo "Warning:	Stored or entered MySQL root password does not work."
					echo "	Make sure the \"mysqlpass\" value in \"/usr/local/nagiosxi/etc/xi-sys.cfg\" and"
					echo "	\"/usr/local/nagiosxi/var/xi-sys.cfg\" is up to date and accurate"
					echo "	or enter in the up to date password when upgrading without the \"-n\" option."
	            	echo "	Skipping updates to MySQL user permissions..."
					exit 1
	            fi
	        fi
	    done
	fi

	dbmaint_doesnt_exist="no"
	if [ "$domysqlupdate" == "yes" ]; then
		result="$(mysql -h $cfg__db_info__nagiosxi__dbserver -u root -p$mysqlpass -sse 'SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = "dbmaint_nagiosxi")')"
		if [ "$result" == "0" ]; then
			dbmaint_doesnt_exist="yes"
		fi
	fi

	root_has_grant="no"
	if [ "$domysqlupdate" == "yes" ] && [ "$dbmaint_doesnt_exist" == "yes" ]; then
		if mysql -h $cfg__db_info__nagiosxi__dbserver -u root -p$mysqlpass -e 'GRANT GRANT OPTION ON *.* TO root@localhost;' &>/dev/null; then
			root_has_grant="yes"
		else
			echo "Error:	Unable to certify if the MySQL root user has the GRANT OPTION permission."
			echo "	When setting up the root user for Nagios XI to use on an offloaded database,"
			echo "	the \"GRANT OPTION\" grant needs to be explicitly set."
			echo "	A possible fix:"
			echo "	Run on server with offloaded database:"
			echo "		\"GRANT ALL ON *.* TO root@'<IP_OF_NAGIOS_XI_SERVER>' WITH GRANT OPTION;"
			exit 1
		fi
	fi

	if [ "$domysqlupdate" == "yes" ] && [ "$dbmaint_doesnt_exist" == "yes" ] && [ "$root_has_grant" == "yes" ] && [ ! -f 'mysql.60002_root.updated' ]; then
		# Sanity Check for dbmaintpass
		if [ -z "$dbmaintpass" ]; then
			dbmaintpass="$(tr -dc '[:alnum:]' < /dev/urandom | head -c 20)"
		fi
		sed -i "s/DBMAINTDEFAULTPASSWORD/$dbmaintpass/" "nagiosxi/nagiosxi-db/mods/mysql/schema_60000_root.sql"

		# Extract hostname from dbserver (remove port if present) for MySQL user grants
		dbserver_host="${cfg__db_info__nagiosxi__dbserver%%:*}"
		# Validate hostname/IP format (basic sanity check)
		if [[ ! "$dbserver_host" =~ ^[a-zA-Z0-9._-]+$ ]] && [[ ! "$dbserver_host" =~ ^[0-9.]+$ ]]; then
			echo "ERROR: Invalid database server hostname: $dbserver_host"
			exit 1
		fi
		sed -i "s|USERDATABASE|$dbserver_host|" "nagiosxi/nagiosxi-db/mods/mysql/schema_60000_root.sql"

		mysql -h $cfg__db_info__nagiosxi__dbserver -u root --password="$mysqlpass" < nagiosxi/nagiosxi-db/mods/mysql/schema_60000_root.sql

		if ! grep -q "dbmaint_user" $proddir/html/config.inc.php ; then
			sed -i "s/\"nagiosxi\" => array(/\"nagiosxi\" => array(\n        \"dbmaint_user\" => 'dbmaint_nagiosxi',\n        \"dbmaint_pwd\" => '$dbmaintpass',/" "$proddir/html/config.inc.php"
		fi
		touch 'mysql.60002_root.updated'
	fi
fi

# XI 2024R1.1
if [ "$oldversion" -lt 60100 ]; then

	echo "Installing Chromium..."
	(
		cd ./subcomponents/chromium
		./install
	)

    # Set up logging files
    echo "Setting log file permissions..."
	touch $proddir/var/chromium_report.log
	chown $apacheuser:$apachegroup $proddir/var/chromium_report.log
	chmod 664 $proddir/var/chromium_report.log

fi

# XI 2024R1.1.3 - Add v2 API rewrite rule
if [ "$oldversion" -lt 60103 ]; then
	newRule="RewriteRule nagiosxi/api/v2/(.*)$ $proddir/html/api/v2/index.php [QSA,NC,L]"
	
	# Add to nagiosxi.conf if not already present
	if ! grep -q "nagiosxi/api/v2" "$httpdconfdir/nagiosxi.conf"; then
		awk "/nagiosxi\/api\/v1/ { print; print \"$newRule\"; next }1" $httpdconfdir/nagiosxi.conf > $httpdconfdir/nagiosxi.conf.new
		mv $httpdconfdir/nagiosxi.conf.new $httpdconfdir/nagiosxi.conf
	fi

	if [ "$distro" == "Debian" ] || [ "$distro" == "Ubuntu" ]; then
		ssl_conf="/etc/apache2/sites-available/default-ssl.conf"
	else
		ssl_conf="$httpdconfdir/ssl.conf"
	fi
	if [ -f $ssl_conf ]; then
		if ! grep -q "nagiosxi/api/v2" "$ssl_conf"; then
			awk "/nagiosxi\/api\/v1/ { print; print \"$newRule\"; next }1" $ssl_conf > "$ssl_conf.new"
			mv "$ssl_conf.new" $ssl_conf
		fi
	fi
fi

# Verify v2 API rewrite rule exists for versions that should have it
if [ "$oldversion" -ge 60103 ]; then
	newRule="RewriteRule nagiosxi/api/v2/(.*)$ $proddir/html/api/v2/index.php [QSA,NC,L]"
	
	# Check and add to nagiosxi.conf if missing
	if ! grep -q "nagiosxi/api/v2" "$httpdconfdir/nagiosxi.conf"; then
		echo "WARNING: v2 API rewrite rule missing from nagiosxi.conf, adding it..."
		awk "/nagiosxi\/api\/v1/ { print; print \"$newRule\"; next }1" $httpdconfdir/nagiosxi.conf > $httpdconfdir/nagiosxi.conf.new
		mv $httpdconfdir/nagiosxi.conf.new $httpdconfdir/nagiosxi.conf
	fi

	# Check SSL conf
	if [ "$distro" == "Debian" ] || [ "$distro" == "Ubuntu" ]; then
		ssl_conf="/etc/apache2/sites-available/default-ssl.conf"
	else
		ssl_conf="$httpdconfdir/ssl.conf"
	fi
	if [ -f $ssl_conf ]; then
		if ! grep -q "nagiosxi/api/v2" "$ssl_conf"; then
			echo "WARNING: v2 API rewrite rule missing from SSL conf, adding it..."
			awk "/nagiosxi\/api\/v1/ { print; print \"$newRule\"; next }1" $ssl_conf > "$ssl_conf.new"
			mv "$ssl_conf.new" $ssl_conf
		fi
	fi

	# raise group_concat_max_len to prevent truncation
	mycnf="/etc/my.cnf"

    if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
        mycnf="/etc/mysql/conf.d/mysql.cnf"
        if [ ! -f $mycnf ]; then
            mycnf="/etc/mysql/my.cnf"
        fi
    fi

    if [ "$dist" == "el8" ] || [ "$dist" == "el9" ]; then
        mycnf="/etc/my.cnf.d/mysql-server.cnf"
    fi

	# Add ldap_ad_integration.log
	if [ ! -f $proddir/var/components/ldap_ad_integration.log ]; then
		touch $proddir/var/components/ldap_ad_integration.log
		chown $apacheuser:$nagiosgroup $proddir/var/components/ldap_ad_integration.log
		chmod 664 $proddir/var/components/ldap_ad_integration.log
	fi

	# Make backup for mysql config
	mycnfbak="$mycnf.bak"
	mycnfnew="$mycnf.new"
	cp -f $mycnf $mycnfbak

	if ! grep -q "group_concat_max_len" $mycnf; then
		sed -i 's/\[mysqld\]/\[mysqld\]\ngroup_concat_max_len=8388608\n/' $mycnf
	fi

	# above update requires a mysql restart to take effect
	if [ "$cfg__db_info__nagiosql__dbserver" = "localhost" ] || [ "$cfg__db_info__nagiosql__dbserver" = "127.0.0.1" ]; then
		./nagiosxi/basedir/scripts/manage_services.sh restart mysqld
	else
		extra_message=<<-EOF

		MANUAL MYSQL RESTART REQUIRED!!
		This upgrade requires a MySQL server restart. Please restart your offloaded MySQL server manually.

		EOF
	fi

	# Updating for logrotate
	touch $proddir/var/chromium_report.log
	chown $nagiosuser:$nagiosgroup $proddir/var/chromium_report.log
	chmod 664 $proddir/var/chromium_report.log

	touch $proddir/var/components/snmptrapsender.log
	chown $apacheuser:$nagiosgroup $proddir/var/components/snmptrapsender.log
	chmod 664 $proddir/var/components/snmptrapsender.log

	# Apply the Core service definition by running the upgrade script to fix offloaded database issues
	UPDATE_CORE=1
fi


if [ "$oldversion" -lt 60105 ]; then

	# Add service dependency exclusions
	mysql -h $cfg__db_info__nagiosql__dbserver -u $cfg__db_info__nagiosql__user --password="$cfg__db_info__nagiosql__pwd" --database=$cfg__db_info__nagiosql__db --force < subcomponents/ccm/db/schema_07.sql

fi

if [ "$oldversion" -lt 60200 ]; then
	(
		cd ./subcomponents/mod_security
		./install
		newRule="ErrorDocument 402 /nagiosxi/ModSecurity.php"
		awk "/<Directory \"\/usr\/local\/nagiosxi\/html\">/ { print; print \"$newRule\"; next }1" $httpdconfdir/nagiosxi.conf > $httpdconfdir/nagiosxi.conf.new
		mv $httpdconfdir/nagiosxi.conf.new $httpdconfdir/nagiosxi.conf
	)

    # apply security patches to nrdp
	UPDATE_NRDP=1

	# raise max_allowed_packet
	if [ "$cfg__db_info__nagiosql__dbserver" = "localhost" ] || [ "$cfg__db_info__nagiosql__dbserver" = "127.0.0.1" ]; then

		mycnf="/etc/my.cnf"

		if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
			mycnf="/etc/mysql/conf.d/mysql.cnf"
			if [ ! -f $mycnf ]; then
				mycnf="/etc/mysql/my.cnf"
			fi
		fi

		if [ "$dist" == "el8" ] || [ "$dist" == "el9" ]; then
			mycnf="/etc/my.cnf.d/mysql-server.cnf"
		fi

		# Make backup for mysql config
		mycnfbak="$mycnf.bak"
		mycnfnew="$mycnf.new"
		cp -f $mycnf $mycnfbak

		grep -q "max_allowed_packet" $mycnf &&
			sed -i 's/max_allowed_packet=.*/max_allowed_packet=512M/g' $mycnf || echo "max_allowed_packet=512M" >> $mycnf

		# above update requires a mysql restart to take effect
		./nagiosxi/basedir/scripts/manage_services.sh restart mysqld
	fi

	# Updated for Mod Security
	UPDATE_SUDOERS=1

	# Update the version in pre flight checking whenever you upgrade Core
	# Upgrade Nagios Core to 4.5.3
	UPDATE_CORE=1

	# Upgrade plugins to 2.4.10
	UPDATE_PLUGINS=1

    # Upgrade NDO to 3.1.1
	UPDATE_NDO=1

	# Update schema for CCM 3.4.0 (MRTG config file mgmt)
	mysql -h $cfg__db_info__nagiosql__dbserver -u $cfg__db_info__nagiosql__user --password="$cfg__db_info__nagiosql__pwd" --database=$cfg__db_info__nagiosql__db --force < subcomponents/ccm/db/schema_08.sql
fi

if [ "$oldversion" -lt 60200 ]; then
	(
		cd ./subcomponents/mod_security
		./install
		newRule="ErrorDocument 402 /nagiosxi/ModSecurity.php"
		awk "/<Directory \"\/usr\/local\/nagiosxi\/html\">/ { print; print \"$newRule\"; next }1" $httpdconfdir/nagiosxi.conf > $httpdconfdir/nagiosxi.conf.new
		mv $httpdconfdir/nagiosxi.conf.new $httpdconfdir/nagiosxi.conf
	)

    # apply security patches to nrdp
	UPDATE_NRDP=1

	# raise max_allowed_packet
	if [ "$cfg__db_info__nagiosql__dbserver" = "localhost" ] || [ "$cfg__db_info__nagiosql__dbserver" = "127.0.0.1" ]; then

		mycnf="/etc/my.cnf"

		if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
			mycnf="/etc/mysql/conf.d/mysql.cnf"
			if [ ! -f $mycnf ]; then
				mycnf="/etc/mysql/my.cnf"
			fi
		fi

		if [ "$dist" == "el8" ] || [ "$dist" == "el9" ]; then
			mycnf="/etc/my.cnf.d/mysql-server.cnf"
		fi

		# Make backup for mysql config
		mycnfbak="$mycnf.bak"
		mycnfnew="$mycnf.new"
		cp -f $mycnf $mycnfbak

		grep -q "max_allowed_packet" $mycnf &&
			sed -i 's/max_allowed_packet=.*/max_allowed_packet=512M/g' $mycnf || echo "max_allowed_packet=512M" >> $mycnf

		# above update requires a mysql restart to take effect
		./nagiosxi/basedir/scripts/manage_services.sh restart mysqld
	fi

	# Updated for Mod Security
	UPDATE_SUDOERS=1

	# Update the version in pre flight checking whenever you upgrade Core
	# Upgrade Nagios Core to 4.5.3
	UPDATE_CORE=1

	# Upgrade plugins to 2.4.10
	UPDATE_PLUGINS=1

    # Upgrade NDO to 3.1.1
	UPDATE_NDO=1

	# Update schema for CCM 3.4.0 (MRTG config file mgmt)
	mysql -h $cfg__db_info__nagiosql__dbserver -u $cfg__db_info__nagiosql__user --password="$cfg__db_info__nagiosql__pwd" --database=$cfg__db_info__nagiosql__db --force < subcomponents/ccm/db/schema_08.sql
fi

# XI 2024R1.2.2
if [ "$oldversion" -lt 60202 ]; then
	# Upgrade plugins to 2.5
	UPDATE_PLUGINS=1

	# Ubuntu 24 is missing some mibs. Manually download them here
	if [ "$dist" == "ubuntu24" ]; then
		cp ./nagiosxi/mibs/* $mibsdir
	fi
fi

# XI 2024R1.3.2
if [ "$oldversion" -lt 60302 ]; then
	UPDATE_NRPE=1
fi

# XI 2024R2
if [ "$oldversion" -lt 70000 ]; then
	UPDATE_CORE=1

	# Do database updates
	if [ ! -f 'mysql.70000.updated' ]; then

		if [ "$cfg__db_info__nagiosxi__dbserver" == "" ]; then
			cfg__db_info__nagiosxi__dbserver="localhost";
		fi

		# Update nagiosxi database
		mysql -h $cfg__db_info__nagiosxi__dbserver -u $cfg__db_info__nagiosxi__user --password="$cfg__db_info__nagiosxi__pwd" --database=$cfg__db_info__nagiosxi__db --force < nagiosxi/nagiosxi-db/mods/mysql/schema_70000.sql

		touch 'mysql.70000.updated'

	fi
fi

# XI 2024R2.1
if [ "$oldversion" -lt 70100 ]; then

	echo "Installing Nagios Mod-Gearman..."
	(
		cd ./subcomponents/nagios-mod-gearman
		./install
	)
	
	if [ "$cfg__db_info__nagiosxi__dbserver" == "" ]; then
		cfg__db_info__nagiosxi__dbserver="localhost";
	fi

	# Get root mysql password
	# Test for pre-saved password (from ./fullinstall script)
	if mysqlshow -h $cfg__db_info__nagiosxi__dbserver -u root -p"$mysqlpass" &>/dev/null; then
	    echo "Saved password worked..."
	    domysqlupdate="yes"
	else
	    for i in 1 2 3; do
	        if [ "$INTERACTIVE" = "True" ]; then
	            # Ask for the password
	            echo "Enter the MySQL root password to continue..."
	            read -p "MySQL Root Password: " pass
	        fi

	        # Test the password
	        if mysqlshow -h $cfg__db_info__nagiosxi__dbserver -u root -p"$pass" &>/dev/null; then
	            echo "Password validated."
	            domysqlupdate="yes"
	            mysqlpass="$pass"
	            break
	        else
	            echo "Password failed." 
	            if [ $i -eq 3 ]; then
	            	echo "Warning:	Stored or entered MySQL root password does not work."
					echo "	Make sure the \"mysqlpass\" value in \"/usr/local/nagiosxi/etc/xi-sys.cfg\" and"
					echo "	\"/usr/local/nagiosxi/var/xi-sys.cfg\" is up to date and accurate"
					echo "	or enter in the up to date password when upgrading without the \"-n\" option."
	            	echo "	Skipping updates to MySQL user permissions..."
					exit 1
	            fi
	        fi
	    done
	fi

	root_has_grant="no"
	if [ "$domysqlupdate" == "yes" ]; then
		if mysql -h $cfg__db_info__nagiosxi__dbserver -u root -p$mysqlpass -e 'GRANT GRANT OPTION ON *.* TO root@localhost;' &>/dev/null; then
			root_has_grant="yes"
		else
			echo "Error:	Unable to certify if the MySQL root user has the GRANT OPTION permission."
			echo "	When setting up the root user for Nagios XI to use on an offloaded database,"
			echo "	the \"GRANT OPTION\" grant needs to be explicitly set."
			echo "	A possible fix:"
			echo "	Run on server with offloaded database:"
			echo "		\"GRANT ALL ON *.* TO root@'<IP_OF_NAGIOS_XI_SERVER>' WITH GRANT OPTION;"
			exit 1
		fi
	fi

	if [ "$domysqlupdate" == "yes" ] && [ "$root_has_grant" == "yes" ] && [ ! -f 'mysql.70100_root.updated' ]; then
		rm -f nagiosxi/nagiosxi-db/mods/mysql/schema_70100_root.sql
		cp -f nagiosxi/nagiosxi-db/mods/mysql/schema_70100_root.sql.in nagiosxi/nagiosxi-db/mods/mysql/schema_70100_root.sql
		
		# Extract hostname from dbserver (remove port if present) for MySQL user grants
		dbserver_host="${cfg__db_info__nagiosxi__dbserver%%:*}"
		if [[ ! "$dbserver_host" =~ ^[a-zA-Z0-9._-]+$ ]] && [[ ! "$dbserver_host" =~ ^[0-9.]+$ ]]; then
			echo "ERROR: Invalid database server hostname: $dbserver_host"
			exit 1
		fi
		sed -i "s|USERDATABASE|$dbserver_host|" "nagiosxi/nagiosxi-db/mods/mysql/schema_70100_root.sql"

		mysql -h $cfg__db_info__nagiosxi__dbserver -u root --password="$mysqlpass" < nagiosxi/nagiosxi-db/mods/mysql/schema_70100_root.sql
		touch 'mysql.70100_root.updated'
	fi

	# Do database updates
	if [ ! -f 'mysql.70100.updated' ]; then

		# Add remote workers table to database
		mysql -h $cfg__db_info__nagiosxi__dbserver -u $cfg__db_info__nagiosxi__user --password="$cfg__db_info__nagiosxi__pwd" --database=$cfg__db_info__nagiosxi__db --force < nagiosxi/nagiosxi-db/mods/mysql/schema_70100.sql
		touch 'mysql.70100.updated'
	fi

	UPDATE_LOGROTATE=1
fi

# XI 2026R1
# TODO: Do we need to do all of this complicated checking every time?
#       If we do, it should be in one place, not repeated in every release with SQL updates.
if [ "$oldversion" -lt 80000 ]; then
	if [ "$cfg__db_info__nagiosxi__dbserver" == "" ]; then
		cfg__db_info__nagiosxi__dbserver="localhost";
	fi

	# Get root mysql password
	# Test for pre-saved password (from ./fullinstall script)
	if mysqlshow -h $cfg__db_info__nagiosxi__dbserver -u root -p"$mysqlpass" &>/dev/null; then
	    echo "Saved password worked..."
	    domysqlupdate="yes"
	else
	    for i in 1 2 3; do
	        if [ "$INTERACTIVE" = "True" ]; then
	            # Ask for the password
	            echo "Enter the MySQL root password to continue..."
	            read -p "MySQL Root Password: " pass
	        fi

	        # Test the password
	        if mysqlshow -h $cfg__db_info__nagiosxi__dbserver -u root -p"$pass" &>/dev/null; then
	            echo "Password validated."
	            domysqlupdate="yes"
	            mysqlpass="$pass"
	            break
	        else
	            echo "Password failed." 
	            if [ $i -eq 3 ]; then
	            	echo "Warning:	Stored or entered MySQL root password does not work."
					echo "	Make sure the \"mysqlpass\" value in \"/usr/local/nagiosxi/etc/xi-sys.cfg\" and"
					echo "	\"/usr/local/nagiosxi/var/xi-sys.cfg\" is up to date and accurate"
					echo "	or enter in the up to date password when upgrading without the \"-n\" option."
	            	echo "	Skipping updates to MySQL user permissions..."
					exit 1
	            fi
	        fi
	    done
	fi

	root_has_grant="no"
	if [ "$domysqlupdate" == "yes" ]; then
		if mysql -h $cfg__db_info__nagiosxi__dbserver -u root -p$mysqlpass -e 'GRANT GRANT OPTION ON *.* TO root@localhost;' &>/dev/null; then
			root_has_grant="yes"
		else
			echo "Error:	Unable to certify if the MySQL root user has the GRANT OPTION permission."
			echo "	When setting up the root user for Nagios XI to use on an offloaded database,"
			echo "	the \"GRANT OPTION\" grant needs to be explicitly set."
			echo "	A possible fix:"
			echo "	Run on server with offloaded database:"
			echo "		\"GRANT ALL ON *.* TO root@'<IP_OF_NAGIOS_XI_SERVER>' WITH GRANT OPTION;"
			exit 1
		fi
	fi

	if [ "$domysqlupdate" == "yes" ] && [ "$root_has_grant" == "yes" ] && [ ! -f 'mysql.80000_root.updated' ]; then
		rm -f nagiosxi/nagiosxi-db/mods/mysql/schema_80000_root.sql
		cp -f nagiosxi/nagiosxi-db/mods/mysql/schema_80000_root.sql.in nagiosxi/nagiosxi-db/mods/mysql/schema_80000_root.sql
		
		# Extract hostname from dbserver (remove port if present) for MySQL user grants
		dbserver_host="${cfg__db_info__nagiosxi__dbserver%%:*}"
		if [[ ! "$dbserver_host" =~ ^[a-zA-Z0-9._-]+$ ]] && [[ ! "$dbserver_host" =~ ^[0-9.]+$ ]]; then
			echo "ERROR: Invalid database server hostname: $dbserver_host"
			exit 1
		fi
		sed -i "s|USERDATABASE|$dbserver_host|" "nagiosxi/nagiosxi-db/mods/mysql/schema_80000_root.sql"

		mysql -h $cfg__db_info__nagiosxi__dbserver -u root --password="$mysqlpass" < nagiosxi/nagiosxi-db/mods/mysql/schema_80000_root.sql
		touch 'mysql.80000_root.updated'
	fi

	# Do database updates
	if [ ! -f 'mysql.80000.updated' ]; then

		# Add tables for new dashboard system
		mysql -h $cfg__db_info__nagiosxi__dbserver -u $cfg__db_info__nagiosxi__user --password="$cfg__db_info__nagiosxi__pwd" --database=$cfg__db_info__nagiosxi__db --force < nagiosxi/nagiosxi-db/mods/mysql/schema_80000.sql
		touch 'mysql.80000.updated'
	fi

	# TODO: Do we need this every time we modify the DB?
	UPDATE_LOGROTATE=1
fi

# XI 2026R1.0.1
if [ "$oldversion" -lt 80001 ]; then

	domysqlupdate="yes"
	root_has_grant="no"

	# TODO: This whole "GRANT" section should be a function, not copied everywhere.
	if [ "$domysqlupdate" == "yes" ]; then
		if mysql -h $cfg__db_info__nagiosxi__dbserver -u root -p$mysqlpass -e 'GRANT GRANT OPTION ON *.* TO root@localhost;' &>/dev/null; then
			root_has_grant="yes"
		else
			echo "Error:	Unable to certify if the MySQL root user has the GRANT OPTION permission."
			echo "	When setting up the root user for Nagios XI to use on an offloaded database,"
			echo "	the \"GRANT OPTION\" grant needs to be explicitly set."
			echo "	A possible fix:"
			echo "	Run on server with offloaded database:"
			echo "		\"GRANT ALL ON *.* TO root@'<IP_OF_NAGIOS_XI_SERVER>' WITH GRANT OPTION;"
			exit 1
		fi
	fi

	if [ "$domysqlupdate" == "yes" ] && [ "$root_has_grant" == "yes" ] && [ ! -f 'mysql.80001_root.updated' ]; then
		rm -f nagiosxi/nagiosxi-db/mods/mysql/schema_80001_root.sql
		cp -f nagiosxi/nagiosxi-db/mods/mysql/schema_80001_root.sql.in nagiosxi/nagiosxi-db/mods/mysql/schema_80001_root.sql
		
		# Extract hostname from dbserver (remove port if present) for MySQL user grants
		dbserver_host="${cfg__db_info__nagiosxi__dbserver%%:*}"
		if [[ ! "$dbserver_host" =~ ^[a-zA-Z0-9._-]+$ ]] && [[ ! "$dbserver_host" =~ ^[0-9.]+$ ]]; then
			echo "ERROR: Invalid database server hostname: $dbserver_host"
			exit 1
		fi
		sed -i "s|USERDATABASE|$dbserver_host|" "nagiosxi/nagiosxi-db/mods/mysql/schema_80001_root.sql"

		mysql -h $cfg__db_info__nagiosxi__dbserver -u root --password="$mysqlpass" < nagiosxi/nagiosxi-db/mods/mysql/schema_80001_root.sql
		touch 'mysql.80001_root.updated'
	fi

	# Do database updates
	if [ ! -f 'mysql.80001.updated' ]; then

		if [ "$cfg__db_info__nagiosxi__dbserver" == "" ]; then
			cfg__db_info__nagiosxi__dbserver="localhost";
		fi

		# Update nagiosxi database
		mysql -h $cfg__db_info__nagiosxi__dbserver -u $cfg__db_info__nagiosxi__user --password="$cfg__db_info__nagiosxi__pwd" --database=$cfg__db_info__nagiosxi__db --force < nagiosxi/nagiosxi-db/mods/mysql/schema_80001.sql

		touch 'mysql.80001.updated'

	fi
fi

# XI 2026R1.0.2
if [ "$oldversion" -lt 80101 ]; then
	# create SSO tables if they don't exist and migrate user meta to database
	if [ "$cfg__db_info__nagiosxi__dbserver" == "" ]; then
		cfg__db_info__nagiosxi__dbserver="localhost";
	fi

	# Ensure all tables are InnoDB before applying schema with foreign keys
	if [ ! -f 'mysql.80002.innodb_migrated' ]; then
		echo "Migrating tables to InnoDB before applying schema_80002.sql..."
		migration_success=0
		if [ -f "./nagiosxi/basedir/scripts/migrate_tables_to_innodb.sh" ]; then
			if bash "./nagiosxi/basedir/scripts/migrate_tables_to_innodb.sh"; then
				touch 'mysql.80002.innodb_migrated'
				migration_success=1
			fi
		else
			echo "WARNING: migrate_tables_to_innodb.sh not found, skipping InnoDB migration"
		fi

		if [ "$migration_success" -eq 0 ] && [ ! -f 'mysql.80002.innodb_migrated' ]; then
			echo "WARNING: InnoDB migration failed or was skipped. Skipping schema_80002.sql update. SSO will not work until this is manually run."
			echo "To run manually, run the following command:"
			echo "bash ./nagiosxi/basedir/scripts/migrate_tables_to_innodb.sh"
			echo "Then run the following command:"
			echo "mysql -h $cfg__db_info__nagiosxi__dbserver -u root -p --database=$cfg__db_info__nagiosxi__db --force < nagiosxi/nagiosxi-db/mods/mysql/schema_80002.sql"
			echo "Then run the following command:"
			echo "touch 'mysql.80002.updated'"
			exit 1
		fi
	fi

	# Apply schema update if migration succeeded and schema hasn't been applied yet
	if [ -f 'mysql.80002.innodb_migrated' ] && [ ! -f 'mysql.80002.updated' ]; then
		# Only modify schema file if USERDATABASE placeholder still exists
		if grep -q "USERDATABASE" "nagiosxi/nagiosxi-db/mods/mysql/schema_80002.sql"; then
			if [ "$cfg__db_info__nagiosxi__dbserver" == "localhost" ]; then
				sed -i "s/USERDATABASE/localhost/" "nagiosxi/nagiosxi-db/mods/mysql/schema_80002.sql"
			else
				# Get IP address to use for offloaded DB's
				ip=$(mysql -h $cfg__db_info__nagiosxi__dbserver -u root -p$mysqlpass -sse "SELECT host FROM mysql.user WHERE user='nagiosxi'")
				if [ -z "$ip" ]; then
					ip=$(ip addr | grep global | grep -m 1 'inet' | awk '/inet[^6]/{print substr($2,0)}' | sed 's|/.*||')
				fi
				if [ -z "$ip" ]; then
					ip=$(ip addr | grep global | grep -m 1 'inet' | awk '/inet6/{print substr($2,0)}' | sed 's|/.*||')
				fi
				sed -i "s/USERDATABASE/$ip/" "nagiosxi/nagiosxi-db/mods/mysql/schema_80002.sql"
			fi
		fi
		mysql -h $cfg__db_info__nagiosxi__dbserver -u root --password="$mysqlpass" --database=$cfg__db_info__nagiosxi__db --force < nagiosxi/nagiosxi-db/mods/mysql/schema_80002.sql && touch 'mysql.80002.updated'
	fi

fi
#####################
# XI 2026R1.2
#####################

if [ "$oldversion" -lt 80200 ]; then

        echo "Building Nagios Core..."
        (
                cd ./subcomponents/nagioscore
                ./upgrade
        )

        echo "Building InfluxDB performance data module..."
        (
                cd ./subcomponents/influx_perfdata
                ./install
        )
		./install-sudoers
fi
##### End of if [ "$oldversion" -lt 80200 ]

#####################
# XI 2026R1.2.1
#####################

if [ "$oldversion" -lt 80201 ]; then

  UPDATE_CORE=1

fi
##### End of if [ "$oldversion" -lt 80201 ]

#####################
# XI 2026R1.5
#####################

if [ "$oldversion" -lt 80500 ]; then

  UPDATE_CORE=1

fi

##### End of if [ "$oldversion" -lt 80500 ]

#####################
# XI 2026R1.7
#####################

if [ "$oldversion" -lt 80700 ]; then
  if [ "$dist" == "ubuntu22" ] || [ "$dist" == "ubuntu24" ] || [ "$dist" == "debian12" ]; then
	echo "extension=ssh2.so" | tee -a $(find /etc/php -name "php.ini" | grep cli)
  fi
	UPDATE_LOGROTATE=1
	UPDATE_CORE=1
	./subcomponents/chromium/install
fi

##### End of if [ "$oldversion" -lt 80700 ]

UPDATE_ADDONS=1 # Always update addons unless we go back to pulling them from the repo again

# Install updated NagiosXI PHP files, scripts, etc. to /usr/local/nagiosxi
# This also makes the latest config perm reset utility
# We need to do this to update the XI html files before we run the install scripts as they rely on the latest files
./install-html

# XI 2026R1.0.2 - migrate SSO user meta after files are installed
if [ "$oldversion" -lt 80101 ]; then
	/usr/bin/php "$proddir/scripts/migrate_sso_user_meta.php" || true
fi

# Clean up trash files from vSphere config wizard (2026R1.0.1)
if [ "$oldversion" -lt 80001 ]; then
	rm -f "$proddir/html/includes/configwizards/vsphere/auth.txt"
	rm -f "$proddir/html/includes/configwizards/vsphere/plugins/check_functions.py"
	rm -f "$proddir/html/includes/configwizards/vsphere/plugins/mycert.pem"
	rm -f "$proddir/html/includes/configwizards/vsphere/plugins/vsphere.code-workspace"
	rm -f "$proddir/html/includes/configwizards/vsphere/scratch.txt"
	rm -f "$proddir/html/includes/configwizards/vsphere/vc_auth.txt"
fi

##########################################################################
## FLAGGED CHANGES
##
## If the version specific updates set these flags, do them now
##########################################################################

if [ $UPDATE_CORE -eq 1 ]; then
	echo "Upgrading Nagios Core..."
	(
		cd ./subcomponents/nagioscore
		./upgrade
	)
fi

# Set check_for_updates to 0 unconditionally for all upgrades. Even when UPDATE_CORE is not 1  
sed -i 's/^check_for_updates=1/check_for_updates=0/' /usr/local/nagios/etc/nagios.cfg

if [ $UPDATE_NDO -eq 1 ]; then
	echo "Upgrading NDO..."
	(
		cd ./subcomponents/ndo
		./upgrade
	)
fi

if [ $UPDATE_NRDP -eq 1 ]; then
	echo "Upgrading NRDP..."
	(
		cd ./subcomponents/nrdp
		./upgrade
	)
fi

if [ $UPDATE_NRPE -eq 1 ]; then
	echo "Upgrading NRPE..."
	(
		cd ./subcomponents/nrpe
		./upgrade
	)
fi

if [ $UPDATE_NSCA -eq 1 ]; then
	echo "Upgrading NSCA..."
	(
		cd ./subcomponents/nsca
		./upgrade
	)
fi

if [ $UPDATE_PNP -eq 1 ]; then
	echo "Upgrading PNP..."
	(
		cd ./subcomponents/pnp
		./upgrade
	)
fi

if [ $UPDATE_PLUGINS -eq 1 ]; then
	echo "Upgrading Nagios Plugins..."
	(
		cd ./subcomponents/nagiosplugins
		./upgrade
	)
fi

# Update MRTG component
if [ $UPDATE_MRTG -eq 1 ]; then
	(
		cp /etc/mrtg/mrtg.cfg /etc/mrtg/mrtg.cfg.upgradebak
		cd ./subcomponents/mrtg
		./upgrade
		mv /etc/mrtg/mrtg.cfg.upgradebak /etc/mrtg/mrtg.cfg
	)
fi

if [ $UPDATE_ADDONS -eq 1 ]; then
	if [ "$INTERACTIVE" = "True" ]; then
		fmt -s -w $(tput cols) <<-EOF
		===================
		XI Add-ons Updates
		===================
		NOTICE: This upgrade script will update ALL XI components, wizards, and dashlets
		to the latest available versions. Before running this upgrade the currently
		installed versions will be backed up to the /tmp directory.

		EOF

		read -p "Are you sure you want to continue? [y/N] " res

	else
		res="Y"
	fi
	# Removing freevariabletab for [GL:XI#151]
	if [ -d /usr/local/nagiosxi/html/includes/components/freevariabletab ] ; then
		rm -fr /usr/local/nagiosxi/html/includes/components/freevariabletab
	fi

	if [ "$res" = "y" -o "$res" = "Y" ]; then
		echo "Proceeding with upgrade..."

		# Update wizards
		echo "Updating XI config wizards..."
		(
			cd ./subcomponents/xiwizards
			./install
		)

		# Update components
		echo "Updating XI components..."
		(
			cd ./subcomponents/xicomponents
			./install
		)

		# Install dashlets
		echo "Updating XI dashlets..."
		(
			cd ./subcomponents/xidashlets
			./install
		)

		# Build and install extra plugins (check_throughput, check_snmp_interface_status)
		# extraplugins needs nagios-plugins build artifacts (utils.o, libnagiosplug.a).
		# If UPDATE_PLUGINS was 0 the nagiosplugins build was skipped, so build
		# (without installing) now to provide those artifacts.
		pkgtar=$(ls ./subcomponents/nagiosplugins/nagios-plugins-2.*.tar.gz 2>/dev/null | head -1)
		pkgname=$(basename "$pkgtar" .tar.gz)
		if [ ! -f "./subcomponents/nagiosplugins/$pkgname/plugins/utils.o" ]; then
			echo "Building nagios-plugins (build artifacts needed by extraplugins)..."
			(
				cd ./subcomponents/nagiosplugins
				rm -rf "$pkgname"
				tar -xzf "$pkgname.tar.gz"
				./apply-patches "$pkgname"
				cd "$pkgname"
				./configure
				make clean
				make
			)
		fi
		(cd ./subcomponents/extraplugins && ./upgrade)
	else
		echo "Upgrade cancelled"
	fi
fi

#####################
# XI 2026R1.3
#####################
# Runs here so xicomponents/install has already deployed the updated nrdsconfigmanager/install.sh
if [ "$oldversion" -lt 80300 ]; then
	if [ -f "$proddir/html/includes/components/nrdsconfigmanager/installed.nrds" ]; then

		nrdp_cfg="/usr/local/nrdp/server/config.inc.php"
		nrdp_cfg_bak="/usr/local/nrdp/server/config.inc.php.bak"
		nrdp_configs_dir="/usr/local/nrdp/configs"
		nrdp_configs_bak="$proddir/tmp/nrdp_configs_upgrade_bak"

		if [ -f "$nrdp_cfg" ]; then
			cp -p "$nrdp_cfg" "$nrdp_cfg_bak"
		fi

		if [ -d "$nrdp_configs_dir" ]; then
		mkdir -p "$nrdp_configs_bak"
		cp -rp "$nrdp_configs_dir/." "$nrdp_configs_bak/"
		fi

		rm -f /tmp/nrds-*.tar.gz
		rm -rf /tmp/nrds
		rm -f /tmp/nsis-*.tar.gz /tmp/nsis_*.tar.gz
		rm -rf /tmp/nsis

		rm -f "$proddir/html/includes/components/nrdsconfigmanager/installed.nrds"
		"$proddir/html/includes/components/nrdsconfigmanager/install.sh"

		if [ -f "$nrdp_cfg_bak" ]; then
		mv "$nrdp_cfg_bak" "$nrdp_cfg"
		fi
		
		if [ -d "$nrdp_configs_bak" ]; then
		cp -rp "$nrdp_configs_bak/." "$nrdp_configs_dir/"
		rm -rf "$nrdp_configs_bak"
		fi
  	fi
fi
##### End of if [ "$oldversion" -lt 80300 ]

if [ $UPDATE_LOGROTATE -eq 1 ]; then
	echo "Updating Logrotate Configuration"
	cp ./nagiosxi/logrotate.nagiosxi /etc/logrotate.d/nagiosxi

	if [ "$dist" == "el9" ]; then
		sed -i "s|APACHEUSER|$apacheuser|;s|NAGIOSGROUP|$nagiosgroup|;s|NAGIOSUSER|$nagiosuser|;s|PRODDIR|/$proddir|" /etc/logrotate.d/nagiosxi
	else
		sed -i "s|APACHEUSER|$apacheuser|;s|NAGIOSGROUP|$nagiosgroup|;s|NAGIOSUSER|$nagiosuser|;s|PRODDIR|$proddir|" /etc/logrotate.d/nagiosxi
	fi

	if `systemctl list-unit-files | grep -q logrotate`; then
		echo "ReadWritePaths=$proddir/var $proddir/tmp" >> /usr/lib/systemd/system/logrotate.service
		systemctl daemon-reload
	fi
fi

# Fix/update sudoers
DOSUDO=0
if [ $UPDATE_SUDOERS -eq 1 ]; then

	if [ "$INTERACTIVE" = "True" ]; then
		fmt -s -w $(tput cols) <<-EOF
		=============================
		SUDOERS FILE REQUIRES UPGRADE
		=============================
		This Nagios XI upgrade requires a change to the sudoers file. If you would like, the
		upgrade can perform this change in your /etc/sudoers.

		You *must* confirm if you can overwrite the sudoers file. If you can't update it,
		a message will show at the end of upgrade to manually update your sudoers file.

		EOF

		read -p "Have upgrade script update sudoers file? [Y/n] " res

	else
		res="Y"
	fi

	if [ "$res" = "" -o "$res" = "y" -o "$res" = "Y" ]; then
		DOSUDO=1
	fi

	if [ $DOSUDO -eq 1 ]; then
		./install-sudoers
	fi

fi

if [ $UPDATE_PHANTOMJS -eq 1 ]; then
	(
		cd ./subcomponents/phantomjs
		./install
	)
fi

##########################################################################
## COMMON FIXES
##
## These run during every upgrade after version-specific upgrade procedures
##########################################################################

# Move old nmg log to new location
NMG_LOG_OLD="/usr/local/nagiosxi/var/components/nmg.log"
NMG_LOG_NEW="/usr/local/nagiosxi/var/nmg.log"

if [ -f "$NMG_LOG_OLD" ]; then
	mv "$NMG_LOG_OLD" "$NMG_LOG_NEW"
	chown $nagiosuser:$nagiosgroup "$NMG_LOG_NEW"
	chmod 644 "$NMG_LOG_NEW"
fi

# Add a UUID if one doesn't already exist
if [ ! -f /usr/local/nagiosxi/var/xi-uuid ]; then
	uuidgen >> /usr/local/nagiosxi/var/xi-uuid
	chown $nagiosuser:$nagiosgroup /usr/local/nagiosxi/var/xi-uuid
fi

# Set up key and cert directories
mkdir -p /usr/local/nagiosxi/var/keys
mkdir -p /usr/local/nagiosxi/var/certs
chown -R $nagiosuser:$nagiosgroup /usr/local/nagiosxi/var/keys
chown -R $nagiosuser:$nagiosgroup /usr/local/nagiosxi/var/certs
chmod 775 /usr/local/nagiosxi/var/keys
chmod 775 /usr/local/nagiosxi/var/certs

# Update old crontab entries
./uninstall-crontab-nagios
./uninstall-crontab-root
install -m 644 nagiosxi/nagiosxi.cron.d /etc/cron.d/nagiosxi

# Fix perms on Backups (make backup directory if it doesn't exist)
mkdir -p /store/backups/nagiosxi
chown $nagiosuser:$nagiosgroup -R /store/backups/nagiosxi

# Fix perms on Nagios etc directory
chown $apacheuser:$nagiosgroup /usr/local/nagios/etc

# XI 2024R2
if [ "$oldversion" -lt 70000 ] && [ -d "$proddir/html/api/v2" ]; then
	# Remove prototype API endpoints from 2024R1.X
	# We're doing this as close as possible to the HTML install.
	# Please don't add any long-running between these steps or Neptune users will experience a crash -SAW
	rm -rf "$proddir/html/api/v2/*"
	cp -r ./nagiosxi/basedir/html/api/v2/* "$proddir/html/api/v2"
fi

# Fix permissions on restore config file
chmod ug+x "$proddir/scripts/nom_restore_nagioscore_checkpoint_specific.sh"

# Install latest PNP templates
./install-pnptemplates
chmod g+w /usr/local/nagios/share/pnp/templates.dist/*.php
chmod g+w /usr/local/nagios/share/pnp/templates/*.php

# Make sure large install tweaks are enabled
echo "Enabling large install tweaks..."
sed -i 's/use_large_installation_tweaks=0/use_large_installation_tweaks=1/g' /usr/local/nagios/etc/nagios.cfg

set +e

# Fix permissions on config files (set +e just in case there are no files in hosts or services folders)
echo "Fixing config file permissions..."
chown $apacheuser:$nagiosgroup /usr/local/nagios/etc/*.cfg
chown $apacheuser:$nagiosgroup /usr/local/nagios/etc/hosts/*.cfg
chown $apacheuser:$nagiosgroup /usr/local/nagios/etc/services/*.cfg
chown -R "$apacheuser:$apachegroup" /var/www/html/nagiosql/config

# Fix permissions in custom-includes
$proddir/html/includes/components/custom-includes/install.sh

set -e

# Set permissions on htpasswd file
echo "Fixing htpasswd permissions..."
chown -R $nagiosuser:$apachegroup "$proddir/etc/htpasswd.users"

# Enforce proper group membership
echo "Checking group memberships..."
eval "$usermodbin" -a -G "$nagioscmdgroup" "$nagiosuser"
eval "$usermodbin" -a -G "$nagioscmdgroup" "$apacheuser"
eval "$usermodbin" -a -G "$nagiosgroup" "$nagiosuser"
eval "$usermodbin" -a -G "$nagiosgroup" "$apacheuser"

# Install new Nagios Core templates (restarts Nagios Core)
./install-templates

# Add changes to apache config
if ! grep -q "{ 'OPTIONS', 'HEAD', 'TRACK' }" $httpdconfdir/nagiosxi.conf ; then
	echo -e "\n<If \"%{REQUEST_METHOD} in { 'OPTIONS', 'HEAD', 'TRACK' }\">\nOrder allow,deny\nDeny from all\n</If>\nTraceEnable off" >> $httpdconfdir/nagiosxi.conf
fi

# Ensure 403/404 use React error page (so 403 vs 404 cannot map the server)
if ! grep -q "ErrorDocument 403" $httpdconfdir/nagiosxi.conf ; then
	{ echo '# 403s and 404s served as 404 via React error page'; echo 'ErrorDocument 403 /nagiosxi/error.php'; echo 'ErrorDocument 404 /nagiosxi/error.php'; cat $httpdconfdir/nagiosxi.conf; } > $httpdconfdir/nagiosxi.conf.tmp && mv $httpdconfdir/nagiosxi.conf.tmp $httpdconfdir/nagiosxi.conf
fi

# Restart apache so it recognizes the new permissions
$proddir/scripts/manage_services.sh restart httpd

# Modify php-fpm configs if clear_env doesn't exist
if [ "$dist" == "el8" ] || [ "$dist" == "el9" ]; then
	if ! grep -q '^clear_env = no' /etc/php-fpm.d/www.conf ; then
    	echo 'clear_env = no' >> /etc/php-fpm.d/www.conf
    fi

	if grep -q '^php_value\[soap\.wsdl_cache_dir\]' /etc/php-fpm.d/www.conf ; then
		sed -i 's/^\(php_value\[soap\.wsdl_cache_dir\]\)/;\1/' /etc/php-fpm.d/www.conf
	fi

	if ! grep -q '^catch_workers_output = yes' /etc/php-fpm.d/www.conf ; then
		# Ensure any worker errors are also seen
		sed -i "s/$(grep 'catch_workers_output =' /etc/php-fpm.d/www.conf)/catch_workers_output = yes/" /etc/php-fpm.d/www.conf
		# Ensure all errors go to www-error.log
		error_log="$(grep 'error_log = ' /etc/php-fpm.conf)"
		error_log="$(echo $error_log | sed -e 's/\//\\\//g')"
		sed -i "s/$error_log/error_log = \/var\/log\/php-fpm\/www-error.log/" /etc/php-fpm.conf
    fi
	$proddir/scripts/manage_services.sh restart php-fpm
fi

# Set SNMP MIB directory perms
if [ -d "$mibsdir" ]; then
	chgrp -R "$nagiosgroup" "$mibsdir"
	chmod g+w -R "$mibsdir"
	chmod g+ws "$mibsdir"
fi

# Tune SNMP settings
$proddir/scripts/tune_snmp.sh

# XI 2024R1.2
if [ "$oldversion" -lt 60200 ]; then
	# Import references to MRTG configuration to the CCM
	/bin/cp -Rf /etc/mrtg/conf.d /etc/mrtg/conf.d.bak
	php ./nagiosxi/basedir/scripts/import_mrtg_configuration.php
	./18-webroot
fi

#Remove Execute permissions(All) and write permissions(Group and Other) nagios.service 
#Should be able to remove this line once nagioscore gets upgraded (currently 4.5.3)
chmod a-x,o-w,g-w '/usr/lib/systemd/system/nagios.service'

# XI 2024R1.4.2 Fixes
if [ "$oldversion" -lt 60402 ]; then
	UPDATE_ADDONS=1

	echo "Installing Chromium..."
	(
		cd ./subcomponents/chromium
		./install
	)

	# Set up logging files
	echo "Setting log file permissions..."
	touch $proddir/var/chromium_report.log
	chown $apacheuser:$apachegroup $proddir/var/chromium_report.log
	chmod 664 $proddir/var/chromium_report.log
fi

# Set permissions on OAuth templates
chown $apacheuser:$nagiosgroup $proddir/html/includes/components/oauth2/access-templates.json

# Sounds permissions get clobbered somewhere after component install - fix them here
chmod 775 $proddir/html/sounds -R
chown $apacheuser:$nagiosgroup $proddir/html/sounds -R

# Install Autodiscovery - ensure jobs directory has correct permissions for apache to write
mkdir -p $proddir/html/includes/components/autodiscovery/jobs
chown $apacheuser:$nagiosgroup $proddir/html/includes/components/autodiscovery/jobs
chmod 775 $proddir/html/includes/components/autodiscovery/jobs

# Make sure the tmp/phpmailer.log (Debugging) has been created and has the correct permissions, owner and group.
touch "$proddir/tmp/phpmailer.log"
chown "$apacheuser:$nagiosgroup" "$proddir/tmp/phpmailer.log"
chmod 0664 "$proddir/tmp/phpmailer.log"

# Make sure the debug log files are writable by apache (in nagios group) for truncation
touch "$proddir/var/xidebug.log"
chown "$nagiosuser:$nagiosgroup" "$proddir/var/xidebug.log"
chmod 0660 "$proddir/var/xidebug.log"
touch "$proddir/var/xidebug.log.backtrace"
chown "$nagiosuser:$nagiosgroup" "$proddir/var/xidebug.log.backtrace"
chmod 0660 "$proddir/var/xidebug.log.backtrace"

# Make sure the var/sso_integration.log exists
touch "$proddir/var/components/sso_integration.log"
chown "$apacheuser:$nagiosgroup" "$proddir/var/components/sso_integration.log"
chmod 0664 "$proddir/var/components/sso_integration.log"

# Fix permissions on plugin directory
chown $apacheuser:$nagiosgroup -R /usr/local/nagios/libexec
chown $nagiosuser:$nagiosgroup /usr/local/nagios/libexec/process_perfdata.pl
chmod ug+rwx -R /usr/local/nagios/libexec
chmod g+s /usr/local/nagios/libexec
chown root:$nagiosgroup /usr/local/nagios/libexec/check_dhcp
chown root:$nagiosgroup /usr/local/nagios/libexec/check_icmp
chmod u+s /usr/local/nagios/libexec/check_dhcp
chmod u+s /usr/local/nagios/libexec/check_icmp

# Fix mrtg data permissions
chown "$apacheuser:$nagiosgroup" /etc/mrtg -R
chmod 775 /etc/mrtg -R
chown "$apacheuser:$nagiosgroup" /var/lib/mrtg -R
chmod 775 /var/lib/mrtg -R

# Sanity Check make sure these binaries don't have nagios write permissions XI:#668 - DA
chmod 554 /usr/local/nagios/bin/nagios*
chmod 554 /usr/local/nagios/bin/npcd*

# Fix profile component directory structure and permissions
mkdir -p /usr/local/nagiosxi/var/components/profile/
chown nagios:nagios /usr/local/nagiosxi/var/components/profile/
chmod 775 /usr/local/nagiosxi/var/components/profile/

# Nagios XI helper dependencies
mkdir -p $proddir/var/nagios/xihelper     
chown -R $apacheuser:$nagiosgroup $proddir/var/nagios/xihelper
chmod 755 $proddir/var/nagios/xihelper
chmod 550 $proddir/html/includes/classifiers/install.sh
chown root:$nagiosgroup $proddir/html/includes/classifiers/install.sh


# Make sure to run the PHP upgrade
php "$proddir/html/upgrade.php"

ip=$(ip addr | grep global | grep -m 1 'inet' | awk '/inet[^6]/{print substr($2,0)}' | sed 's|/.*||')

if [ "$ip" == "" ]; then
    ip=$(ip addr | grep global | grep -m 1 'inet' | awk '/inet6/{print substr($2,0)}' | sed 's|/.*||')
    ip="[$ip]"
fi

if [ "$ip" == "" ];then
    ip="<HOSTNAME>"
fi

if [ -r /etc/sysconfig/clock ]; then
    . /etc/sysconfig/clock
    timezone="$ZONE"
elif [ `command -v timedatectl` ]; then
    timezone=$(timedatectl | awk '/Time zone:/ {print $3}')
fi

# Set php.ini defaults
echo "Checking php.ini defaults..."
for file in $(find /etc -name "php.ini"); do
    echo "Checking max_execution_time for PHP in $file..."
    if ! execution_time_line=$(grep "^max_execution_time =" $file); then
        # Uncommented line not found, look for commented line, replace with our configuration
        if execution_time_line=$(grep "^;max_execution_time =" $file); then
            commented_execution_time_line=$(echo $execution_time_line | tail -n 1)
            echo "Found commented max_execution_time value, setting to 600..."
            sed -i "s/$commented_execution_time_line/max_execution_time = 600/g" $file
        fi
    else
        execution_time=$(echo $execution_time_line | awk '{print $3}')
        if [ ! -z "$execution_time_line" ] && ([[ $execution_time_line = ";"* ]] || [ "$execution_time" -lt "600" ]); then
            echo "max_execution_time is less than 600 in $file, setting to 600..."
            sed -i "s/$execution_time_line/max_execution_time = 600/g" $file
        fi
    fi

    # Check max_input_time
    echo "Checking max_input_time for PHP in $file..."
    if ! max_input_time_line=$(grep "^max_input_time =" $file); then
        # Uncommented line not found, look for commented line, replace with our configuration
        if max_input_time_line=$(grep "^;max_input_time =" $file); then
            commented_max_input_time_line=$(echo $max_input_time_line | tail -n 1)
            echo "Found commented max_input_time value, setting to 1200..."
            sed -i "s/$commented_max_input_time_line/max_input_time_line = 1200/g" $file
        fi
    else
        input_time=$(echo $max_input_time_line | awk '{print $3}')
        if [ ! -z "$max_input_time_line" ] && ([[ $max_input_time_line = ";"* ]] || [ "$input_time" -lt "1200" ]); then
            echo "max_input_time is less than 1200 in $file, setting to 1200..."
            sed -i "s/$max_input_time_line/max_input_time = 1200/g" $file
        fi
    fi

    # Check max_input_vars
    echo "Checking max_input_vars for PHP in $file..."
    if ! max_input_vars_line=$(grep "^max_input_vars =" $file); then
        # Uncommented line not found, look for commented line, replace with our configuration
        if max_input_vars_line=$(grep "^;max_input_vars =" $file); then
            commented_max_input_vars_line=$(echo $max_input_vars_line | tail -n 1)
            echo "Found commented max_input_vars value, setting to 50000..."
            sed -i "s/$commented_max_input_vars_line/max_input_vars = 50000/g" $file
        fi
    else
        input_vars=$(echo $max_input_vars_line | awk '{print $3}')
        if [ ! -z "$max_input_vars_line" ] && ([[ $max_input_vars_line = ";"* ]] || [ "$input_vars" -lt "50000" ]); then
            echo "max_input_vars is less than 50000 in $file, setting to 50000..."
            sed -i "s/$max_input_vars_line/max_input_vars = 50000/g" $file
        fi
    fi

    # Check memory_limit
    echo "Checking memory_limit for PHP in $file..."
    if ! memory_limit_line=$(grep "^memory_limit =" $file); then
        # Uncommented line not found, look for commented line, replace with our configuration
        if memory_limit_line=$(grep "^;memory_limit =" $file); then
            commented_memory_limit_line=$(echo $memory_limit_line | tail -n 1)
            echo "Found commented memory_limit value, setting to 1024M..."
            sed -i "s/$commented_memory_limit_line/memory_limit = 1024M/g" $file
        fi
    else
        memory_limit=$(echo $memory_limit_line | awk '{print $3}')
        # Extract the integer value from the memory limit
        int_memory_limit=$(echo $memory_limit | sed 's/[^0-9]*//g')
        # Compare the extracted integer value with another value
        if [ ! -z "$memory_limit_line" ] && ([[ $memory_limit_line = ";"* ]] || [ "$int_memory_limit" -lt 1024 ]); then
            echo "memory_limit is less than 1024M in $file, setting to 1024M..."
            sed -i "s/$memory_limit_line/memory_limit = 1024M/g" $file
        fi
    fi

	# Set timezone
	if [ -n $timezone ]; then
        echo "Setting date.timezone for PHP in $file..."
        sed -i "s|^;date\.timezone =.*|date.timezone = $timezone|" "$file" || true
    fi
done

# If the server has nagiosim and reactoreventhandler components installed, they need to be removed as they are discontinued and so they do not generate "PHP Notice: DB is not connected" messages.
if [ -d "/usr/local/nagiosxi/html/includes/components/nagiosim" ]; then
  mv -f /usr/local/nagiosxi/html/includes/components/nagiosim ~/nagiosim.backup
fi

if [ -d "/usr/local/nagiosxi/html/includes/components/reactoreventhandler" ]; then
  mv -f /usr/local/nagiosxi/html/includes/components/reactoreventhandler ~/reactoreventhandler.backup
fi

if [ "$oldversion" -lt 60104 ]; then
	php /usr/local/nagiosxi/scripts/mark_update_command_as_complete.php
fi

cat <<-EOF

	Nagios XI Upgrade Complete!
	---------------------------
	$extra_message
	You can access the Nagios XI web interface by visiting:
	    http://$ip/nagiosxi/

EOF

cat upgrade.log  | gzip -c | dd of=/root/.xi.upgrade.`date +%s`.gz 

# If they are doing manual sudoers update
if [ $UPDATE_SUDOERS -eq 1 ] && [ $DOSUDO -eq 0 ]; then
	echo "============================="
	echo "MANUALLY UPDATE SUDOERS FILE"
	echo "============================="
	echo ""
	echo "Copy new sudo permissions from '$BASEDIR/nagiosxi/nagiosxi.sudoers' to the"
	echo "/etc/sudoers file."
	echo ""
fi
