#!/bin/bash -e

cd $(dirname $(readlink -e "$0"))
. ./libinstall.sh

# Explicitly set umask
umask 0022

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

path='nagioslogserver'
proddir="/var/www/html/nagioslogserver"
backenddir="/usr/local/nagioslogserver"

do_upgrade_check

#source the old version number
. "$proddir/lsversion"
oldversion=$VERSION

# NLS 20224R2+ an only be upgraded from an R2 version or newer
if [ $oldversion -lt 4000 ] ; then 
    echo "The existing version of Nagios Log Server cannot be ugraded to this version."
    echo "See https://assets.nagios.com/downloads/nagios-log-server/docs/Migrating-to-Nagios-Log-Server-2024R2.pdf"
    echo "for more details."
    exit 1
fi

if [ $oldversion -lt 4002 ]; then
	# php-ldap already installed in prereqs
	if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
		ldap_config="/etc/ldap/ldap.conf"
		ldap_dir="/etc/ldap"
		cacerts_dir="/etc/ldap/cacerts"
	else
		ldap_config="/etc/openldap/ldap.conf"
		ldap_dir="/etc/openldap"
		cacerts_dir="/etc/openldap/cacerts"
	fi


	# Edit line in ldap config
	sed -i 's/^TLS_CACERTDIR/#TLS_CACERTDIR/g' $ldap_config
	if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
		echo "TLS_CACERTDIR $ldap_dir/cacerts" >> $ldap_config
	fi

    get_ip

    # Edit line in rsyslog config
    sed -i "s/Target=\"localhost\"/Target=\"$ip\"/g" /etc/rsyslog.d/nagioslogserver.conf
	if [ `command -v firewalld` ]; then
		systemctl restart rsyslog
	else
		service rsyslog restart
	fi

    # Move the OpenSearch Password out of config.local.php
    opensearchpassline=`grep opensearch_password $proddir/application/config/config.local.php`
    if [ ${#opensearchpassline} -ge 0 ]; then
        echo '<?php' > $backenddir/opensearch/config/opensearch_config.php
        echo $opensearchpassline >> $backenddir/opensearch/config/opensearch_config.php
        sed -i "s/\$config\['opensearch_password'\].*//" $proddir/application/config/config.local.php
        echo "include_once(\$config['backend_dir'].'/opensearch/config/opensearch_config.php');" >> $proddir/application/config/config.local.php
    fi
fi

if [ $oldversion -lt 4003 ]; then
    # Remove the node.roles line from the opensearch config file.
    sed -i 's/^node\.roles:.*//g' $backenddir/opensearch/config/opensearch.yml
fi

if [ $oldversion -lt 5002 ]; then
    # In the event that the user changed Logstash to run as root, change it back to nagios.
    sed -i "s/^User=root/User=$nagiosuser/g" /usr/lib/systemd/system/logstash.service
    sed -i "s/^User=root/User=$nagiosuser/g" /usr/lib/systemd/logstash.service
    systemctl daemon-reload

    # Restart logstash
    if [ `command -v systemctl` ]; then
        systemctl restart logstash
    else
        service logstash restart
    fi

fi

chmod 664 $backenddir/opensearch/config/opensearch.yml

#source the new number
. "$path/basedir/html/lsversion"
newversion=$VERSION

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

DISTRO INFO:
$distro
$version
$architecture

Old Version: $oldversion
New Version: $newversion
"

OPENSEARCH_UPDATED=0
LOGSTASH_UPDATED=0
NCPA_UPDATED=0
INTERACTIVE="True"

# Make sure php-dev/php-devel is added
if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
    if [ "$distro" == "Ubuntu" ] && [ -f /etc/apt/sources.list.d/debian.list ]; then
        rm /etc/apt/sources.list.d/debian.list
    fi

    apt-get -y install php-dev

    if [ "$dist" == "ubuntu24" ]; then
        apt-get install -y tzdata-legacy
    fi
else
    # This package is only unavailable on rhel/oracle 7
    yum install -y php-devel
fi

# Install sourceguardian and restart Apache/php-fpm
install_sourceguardian
if [ `command -v systemctl` ]; then
    systemctl restart $httpd

    # systemctl status returns 0 if php-fpm exists, 4 if php-fpm is not a service
    set +e
    systemctl status php-fpm >/dev/null 2>&1
    has_php_fpm=$?
    set -e
    if [ "x$has_php_fpm" = "x0" ]; then
        systemctl restart php-fpm
    fi
else
    service $httpd restart
    # Note: As of March 2023, php-fpm is only installed on systemd-based distros
    # Init-based systems are also using mod_php, so just restarting apache should be sufficient.
fi

# Verify server has needed prereqs
if [ "$oldversion" -ge 200 ]; then

    /usr/bin/php $proddir/www/index.php install/verify_prereqs

fi



#### VERSION SPECIFIC UPDATES ##########

# NLS 20224R2+ an only be upgraded from an R2 version or newer
if [ $oldversion -eq 4000 ] ; then 
    # Regenerate the OpenSearch node certificate.
    ./subcomponents/opensearch/regenerate-host-cert.sh

    # Delete the old ISM based index closing/deletion policy.
    nlspass=`grep opensearch_password /var/www/html/nagioslogserver/application/config/config.local.php | sed "s/.* = '\(.*\)';/\1/"`
    curl -u nagioslogserver:$nlspass --cacert /usr/local/nagioslogserver/opensearch/config/root-ca.pem -XDELETE https://localhost:9200/_plugins/_ism/policies/nagioslogserver_auto_close_index > /dev/null 2>&1

    systemctl restart opensearch
fi



if [ $oldversion -lt 3304 ]; then
    get_ip

    systemctl stop elasticsearch

    # Convert elasticserch service to a systemd based service
    if [ -d "/usr/lib/systemd" ] ; then
        cp -prf subcomponents/elasticsearch/mods/etc/systemd/* /usr/lib/systemd
        cp -prf subcomponents/elasticsearch/mods/etc/systemd/* /usr/lib/systemd/system
    fi

    cp -p subcomponents/elasticsearch/mods/elasticsearch/elasticsearch.in.sh /usr/local/nagioslogserver/elasticsearch/bin

    systemctl daemon-reload
    systemctl enable elasticsearch
    systemctl start elasticsearch

    # Edit line in rsyslog config
    sed -i "s/Target=\"localhost\"/Target=\"$ip\"/g" /etc/rsyslog.d/nagioslogserver.conf
	if [ `command -v firewalld` ]; then
		systemctl restart rsyslog
	else
		service rsyslog restart
	fi

    if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
		ldap_config="/etc/ldap/ldap.conf"
		ldap_dir="/etc/ldap"
		cacerts_dir="/etc/ldap/cacerts"
	else
		ldap_config="/etc/openldap/ldap.conf"
		ldap_dir="/etc/openldap"
		cacerts_dir="/etc/openldap/cacerts"
	fi

	# Edit line in ldap config
	sed -i 's/^TLS_CACERTDIR/#TLS_CACERTDIR/g' $ldap_config
	if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
		echo "TLS_CACERTDIR $ldap_dir/cacerts" >> $ldap_config
	fi

fi

if [ $oldversion -lt 3305 ]; then
    DATA_DIR='"/usr/local/nagioslogserver/elasticsearch/data"'
    # Determine existing ES dta directory
    if [ -f /etc/sysconfig/elasticsearch ]; then
        DATA_DIR=`grep DATA_DIR /etc/sysconfig/elasticsearch | sed "s/DATA_DIR=//"`
    elif [ -f /etc/default/elasticsearch ]; then
        DATA_DIR=`grep DATA_DIR /etc/default/elasticsearch | sed "s/DATA_DIR=//"`
    fi

    sed -i "s#^DATA_DIR=.*#DATA_DIR=$DATA_DIR#g" /usr/local/nagioslogserver/elasticsearch/bin/elasticsearch.in.sh

    systemctl restart elasticsearch
fi

##### ALL VERSION UPDATES ##############


# ---------------------------------
# Update sudoers if it needs it
# ---------------------------------
sudoers

# update cron
sed -i "s/@APACHE@/$apacheuser/g" nagioslogserver/nagioslogserver.cron.d
install -m 644 nagioslogserver/nagioslogserver.cron.d /etc/cron.d/nagioslogserver 

# Copy source directory to the system
/bin/cp -f "$proddir/application/config/config.local.php" /tmp
/bin/rm -rf "$proddir/system"
/bin/rm -rf "$proddir/application/controllers"
/bin/rm -rf "$proddir/application/models"
/bin/rm -rf "$proddir/application/views"
/bin/rm -rf "$proddir/application/libraries"
/bin/cp -rf nagioslogserver/basedir/html/* "$proddir"

/bin/mv -f /tmp/config.local.php "$proddir/application/config/"

# Copy new data files to log server
/bin/cp -rf nagioslogserver/basedir/etc/* "$backenddir/etc"

# Copy backend directory scripts and replace permissions
/bin/cp -rf nagioslogserver/basedir/scripts/* "$backenddir/scripts"
chown -R nagios:nagios "$backenddir"
chmod -R 0775 "$backenddir"
chmod 0554 $backenddir/scripts/*
for script in change_timezone.sh reconfigure_ncpa.sh get_logstash_ports.sh profile.sh reconfigure_ncpa.sh; do
    chown root:root $backenddir/scripts/$script
done

# Set up permissions
for dir in application/cache application/config application/logs application/dashboards www/media; do
    mkdir -p "$proddir/$dir"
    chgrp -R $apachegroup "$proddir/$dir"
    chmod -R g+rwx  "$proddir/$dir"
done

# Run the upgrade script to import new system dashboards
/usr/bin/php $proddir/www/index.php install/upgrade/$oldversion

if [ $oldversion -lt 4003 ]; then
    chmod 0754 /usr/local/nagioslogserver/logstash/jdk/bin/java
    setcap cap_net_bind_service=+ep /usr/local/nagioslogserver/logstash/jdk/bin/java
    systemctl restart logstash
fi

if [ $oldversion -lt 4004 ]; then
    cp subcomponents/ncpa/plugins/* /usr/local/ncpa/plugins/
    chmod 755 /usr/local/ncpa/plugins/*
    # This will still use the hardcoded names from NCPA's original installation
    chown nagios:nagios /usr/local/ncpa/plugins/*
fi

if [ $oldversion -lt 5001 ]; then
    for f in $backenddir/* ; do
        if [[ "$f" != "$backenddir/opensearch" && "$f" != "$backenddir/logstash" ]]; then
            chmod -R og-w "$f"
        fi
    done
	chmod -R 0664 "$backenddir/var"
	chmod 775 "$backenddir/var"
	chmod 0554 $backenddir/scripts/*
fi

if [ $oldversion -lt 5003 ]; then
    # Remove log rotation file
    rm -f /etc/logrotate.d/nagioslogserver

    if [ $OPENSEARCH_UPDATED -eq 0 ]; then
        (
            cd subcomponents/opensearch
            ./upgrade "$distro" "$dist"
        )
        OPENSEARCH_UPDATED=1
    fi

    if [ $LOGSTASH_UPDATED -eq 0 ]; then
        (
            cd subcomponents/logstash
            ./upgrade "$distro" "$dist"
        )
        LOGSTASH_UPDATED=1
    fi
fi


# Special Logstash changes
if [ $LOGSTASH_UPDATED -eq 1 ]; then

    echo "Re-applying logstash configuration..."
    /usr/bin/php $proddir/www/index.php configure/write_configs_for_node

    # Restart logstash
    if [ `command -v systemctl` ]; then
        systemctl restart logstash
    else
        service logstash restart
    fi

fi

# Set php.ini defaults
echo "Checking php.ini defaults..."
for file in $(find /etc -name "php.ini"); do
	# Check memory_limit
    echo "Checking memory_limit for PHP in $file..."
    memory_limit=$(grep "memory_limit" $file | 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 [ -n "$int_memory_limit" ]; then
        if [ "$int_memory_limit" -lt "1024" ]; then
            echo "memory_limit is less than 1024M in $file, setting to 1024M..."
            sed -i 's/memory_limit = .*/memory_limit = 1024M/g' $file
        fi
    fi
done

#### After Upgrade Final Changes ####

update_java_logging_configs

#### Complete Upgrade ####


echo
echo "Nagios Log Server Upgrade Complete!"
echo

if [ -n "$path" ]; then
    get_ip
    
    echo "You can access the Nagios Log Server web interface by visiting:"
    echo "    http://$ip/$path/"
    echo
fi
