#!/bin/bash -e


# get current working directory
BASEDIR=$(dirname $(readlink -f $0))

# Fix for *early* beta testers
if [ -f /usr/local/nagiosfusion/var/version ]; then
    mv /usr/local/nagiosfusion/var/version /usr/local/nagiosfusion/var/fusionversion
fi


# Create setup environment
pushd ./setup/
. ./init.sh
. ./fusion-sys.cfg
. ./functions.sh
oldversion=`./get-version.sh`
popd


# Get config variables
"$BASEDIR/fusion/scripts/import_fusionconfig.php" > "$BASEDIR/config.dat"
. "$BASEDIR/config.dat"
rm "$BASEDIR/config.dat"


# Update this in the corresponding [release].sh
# To force the update of the sudoers file
UPDATE_SUDOERS=0


# Upgrade log
log="$BASEDIR/upgrade.log"


# Initialize upgrade.log
cat >> "$log" <<-EOF
Nagios Fusion Upgrade Log
==============================
DATE: $(date)

DISTRO INFO:
$distro
$version
$architecture

EOF


# Do OS check for the following EOL distros
# Ubuntu 16, 18, 20
# Debian 9, 10
# Centos/RHEL 5, 6, 7
case "$dist" in
    ubuntu20 )
        {
        echo "------------------------------"
        echo " Ubuntu 20 - End of Life"
        echo "------------------------------"
        echo ""
        echo "Nagios Fusion no longer supports Ubuntu 20 due to it being EOL as of 5/31/2025."
        echo "If you'd like to upgrade Nagios Fusion, you can follow these general steps:"
        echo ""
        echo "  1) Perform a Fusion Backup from this (old) server"
        echo "  2) Install Ubuntu 22 or 24 on another (new) server"
        echo "  3) Install Nagios Fusion on the (new) server"
        echo "  4) Copy the backup files to the (new) server"
        echo "  4) Perform a Fusion Restore on the (new) server"
        echo ""
        echo "Or for more detailed information on how to transition, please visit "
        echo "the Nagios support forum:"
        echo "https://support.nagios.com/forum/"
        echo ""
        } | tee -a "$log"
        exit 1
        ;;
    ubuntu18 )
        {
        echo "------------------------------"
        echo " Ubuntu 18 - End of Life"
        echo "------------------------------"
        echo ""
        echo "Nagios Fusion no longer supports Ubuntu 18 due to it being EOL as of 5/31/2023."
        echo "If you'd like to upgrade Nagios Fusion, you can follow these general steps:"
        echo ""
        echo "  1) Perform a Fusion Backup from this (old) server"
        echo "  2) Install Ubuntu 20 or 22 on another (new) server"
        echo "  3) Install Nagios Fusion on the (new) server"
        echo "  4) Copy the backup files to the (new) server"
        echo "  4) Perform a Fusion Restore on the (new) server"
        echo ""
        echo "Or for more detailed information on how to transition, please visit "
        echo "the Nagios support forum:"
        echo "https://support.nagios.com/forum/"
        echo ""
        } | tee -a "$log"
        exit 1
        ;;
    ubuntu16 )
        {
        echo "------------------------------"
        echo " Ubuntu 16 - End of Life"
        echo "------------------------------"
        echo ""
        echo "Nagios Fusion no longer supports Ubuntu 16 due to it being EOL as of 4/30/2021."
        echo "If you'd like to upgrade Nagios Fusion, you can follow these general steps:"
        echo ""
        echo "  1) Perform a Fusion Backup from this (old) server"
        echo "  2) Install Ubuntu 20 or 22 on another (new) server"
        echo "  3) Install Nagios Fusion on the (new) server"
        echo "  4) Copy the backup files to the (new) server"
        echo "  4) Perform a Fusion Restore on the (new) server"
        echo ""
        echo "Or for more detailed information on how to transition, please visit "
        echo "the Nagios support forum:"
        echo "https://support.nagios.com/forum/"
        echo ""
        } | tee -a "$log"
        exit 1
        ;;
    debian10 )
        {
        echo "------------------------------"
        echo " Debian 10 - End of Life"
        echo "------------------------------"
        echo ""
        echo "Nagios Fusion no longer supports Debian 10 due to it being EOL as of 6/30/2024."
        echo "If you'd like to upgrade Nagios Fusion, you can follow these general steps:"
        echo ""
        echo "  1) Perform a Fusion Backup from this (old) server"
        echo "  2) Install Debian 11 or 12 on another (new) server"
        echo "  3) Install Nagios Fusion on the (new) server"
        echo "  4) Copy the backup files to the (new) server"
        echo "  4) Perform a Fusion Restore on the (new) server"
        echo ""
        echo "Or for more detailed information on how to transition, please visit "
        echo "the Nagios support forum:"
        echo "https://support.nagios.com/forum/"
        echo ""
        } | tee -a "$log"
        exit 1
        ;;
    debian9 )
        {
        echo "------------------------------"
        echo " Debian 9 - End of Life"
        echo "------------------------------"
        echo ""
        echo "Nagios Fusion no longer supports Debian 9 due to it being EOL as of 6/30/2022."
        echo "If you'd like to upgrade Nagios Fusion, you can follow these general steps:"
        echo ""
        echo "  1) Perform a Fusion Backup from this (old) server"
        echo "  2) Install Debian 11 or 12 on another (new) server"
        echo "  3) Install Nagios Fusion on the (new) server"
        echo "  4) Copy the backup files to the (new) server"
        echo "  4) Perform a Fusion Restore on the (new) server"
        echo ""
        echo "Or for more detailed information on how to transition, please visit "
        echo "the Nagios support forum:"
        echo "https://support.nagios.com/forum/"
        echo ""
        } | tee -a "$log"
        exit 1
        ;;
    el8 )
        if [ "$distro" == "CentOS" ]; then
            {
            echo "------------------------------"
            echo " CentOS Stream 8 - End of Life"
            echo "------------------------------"
            echo ""
            echo "Nagios Fusion no longer supports CentOS Stream 8 due to it being EOL as of 05/31/2024."
            echo "If you'd like to upgrade Nagios Fusion, you can follow these general steps:"
            echo ""
            echo "  1) Perform a Fusion Backup from this (old) server"
            echo "  2) Install CentOS Stream 9, RHEL/Oracle 8 or 9 on another (new) server"
            echo "  3) Install Nagios Fusion on the (new) server"
            echo "  4) Copy the backup files to the (new) server"
            echo "  4) Perform a Fusion Restore on the (new) server"
            echo ""
            echo "Or for more detailed information on how to transition, please visit "
            echo "the Nagios support forum:"
            echo "https://support.nagios.com/forum/"
            echo ""
            } | tee -a "$log"
            exit 1
        fi
        ;;
    el7 )
        {
        echo "------------------------------"
        echo " CentOS/RHEL 7 - End of Life"
        echo "------------------------------"
        echo ""
        echo "Nagios Fusion no longer supports CentOS/RHEL 7 due to it being EOL as of 06/30/2024."
        echo "If you'd like to upgrade Nagios Fusion, you can follow these general steps:"
        echo ""
        echo "  1) Perform a Fusion Backup from this (old) server"
        echo "  2) Install CentOS Stream 9, RHEL/Oracle 8 or 9 on another (new) server"
        echo "  3) Install Nagios Fusion on the (new) server"
        echo "  4) Copy the backup files to the (new) server"
        echo "  4) Perform a Fusion Restore on the (new) server"
        echo ""
        echo "Or for more detailed information on how to transition, please visit "
        echo "the Nagios support forum:"
        echo "https://support.nagios.com/forum/"
        echo ""
        } | tee -a "$log"
        exit 1
        ;;
    el6 )
        {
        echo "------------------------------"
        echo " CentOS/RHEL 6 - End of Life"
        echo "------------------------------"
        echo ""
        echo "Nagios Fusion no longer supports CentOS/RHEL 6 due to it being EOL as of 11/30/2020."
        echo "If you'd like to upgrade Nagios Fusion, you can follow these general steps:"
        echo ""
        echo "  1) Perform a Fusion Backup from this (old) server"
        echo "  2) Install CentOS/RHEL 7, 8, or 9 on another (new) server"
        echo "  3) Install Nagios Fusion on the (new) server"
        echo "  4) Copy the backup files to the (new) server"
        echo "  4) Perform a Fusion Restore on the (new) server"
        echo ""
        echo "Or for more detailed information on how to transition, please visit "
        echo "the Nagios support forum:"
        echo "https://support.nagios.com/forum/"
        echo ""
        } | tee -a "$log"
        exit 1
        ;;
    el5 )
        {
        echo "------------------------------"
        echo " CentOS/RHEL 5 - End of Life"
        echo "------------------------------"
        echo ""
        echo "Nagios Fusion no longer supports CentOS/RHEL 5 due to it being EOL as of 3/31/2017."
        echo "If you'd like to upgrade Nagios Fusion, you can follow these general steps:"
        echo ""
        echo "  1) Perform a Fusion Backup from this (old) server"
        echo "  2) Install CentOS/RHEL 7, 8, or 9 on another (new) server"
        echo "  3) Install Nagios Fusion on the (new) server"
        echo "  4) Copy the backup files to the (new) server"
        echo "  4) Perform a Fusion Restore on the (new) server"
        echo ""
        echo "Or for more detailed information on how to transition, please visit "
        echo "the Nagios support forum:"
        echo "https://support.nagios.com/forum/"
        echo ""
        } | tee -a "$log"
        exit 1
        ;;
esac

# Installation is interactive by default
export INTERACTIVE="True"

# Force addon upgrade is turned off by default
export FORCE_ADDON_UPGRADE="False"

# Add /usr/sbin and /sbin to PATH if it doesn't exist
if ! path_is_ok; then

    {
    echo "Your system \$PATH does not include /sbin and /usr/sbin."
    echo "Adding /sbin and /usr/sbin to \$PATH."
    } | tee -a "$log"

    PATH="$PATH:/usr/sbin:/sbin"
fi

while [ -n "$1" ]; do
    case "$1" in
        -h | --help)
            usage
            exit 0
            ;;
        -v | --version)
            sed -n '/full/ s/.*=//p' "${0%/*}/fusion/var/fusionversion"
            exit 0
            ;;
        -n | --non-interactive)
            export INTERACTIVE="False"
            ;;
        -f | --force-addon-update)
            # Force update of components, wizards, dashlets
            export FORCE_ADDON_UPGRADE="True"
            ;;
        *)
            echo "Unknown option:  $1" >&2
            usage >&2
            exit 1
    esac
    shift
done


if [ "$INTERACTIVE" = "True" ]; then
    {
    fmt -s -w $(tput cols) <<-EOF

======================
Nagios Fusion Upgrader
======================

This script will perform an upgrade of Nagios Fusion by executing all necessary sub-scripts.

A complete backup will be created and be made available.

EOF
    } | tee -a "$log"

    read -p "Do you want to continue? [Y/n] " res

    case "$res" in
        Y | y | "")
            echo "Proceeding with installation..."
            ;;
        *)
            echo "Installation cancelled"
            exit 0
    esac
fi


# Create backup directory (just in case)
ts=`date +%s`
BAKDIR="/tmp/fusionupgradebackup.$ts"
mkdir -p "$BAKDIR"


# Stop cron from running and kill all of the cron jobs
# - Don't kill the cmd_subsys job though, because this may be running an upgrade
echo "Stopping cron, killing existing cron jobs"
pids=$(ps aux | grep php | grep fusion | grep cron | grep -v cmd_subsys | awk '{ print $2 }')
if [ "$pids" != "" ]; then
    echo $pids | xargs kill
fi
if [ -f "$proddir/scripts/manage_services.php" ]; then
    "$proddir/scripts/manage_services" stop crond
else
    service crond stop >/dev/null 2&>1 ||:
fi


# Install sourceguardian extension
pushd ./setup/
touch installed.basedir
run_sub ./06-sourceguardian.sh
rm installed.basedir
popd


##########################################################################
## VERSION SPECIFIC FIXES
##
## The upgrade scripts in setup/upgrades are executed (in release order)
## Only relevant scripts are executed (depending on current version)
##
##########################################################################

pushd ./setup/upgrades/

# Pre Fusion 2014 R1.1
# (No upgrade available)
. "./0301.sh"

# Fusion 2014 R1.1
. "./0400.sh"

# Fusion4 Tech Preview
. "./3995.sh"

# Fusion4 RC1
. "./3996.sh"

# Fusion4 RC2
. "./3997.sh"

# Fusion4
. "./4000.sh"

# Fusion 4.1
. "./4100.sh"

# Fusion 4.1.3
. "./4103.sh"

# Fusion 4.2.0
. "./4200.sh"

# Fusion 2024R1.1
. "./5100.sh"

# Fusion 2024R2
. "./6000.sh"

popd


##########################################################################
## COMMON FIXES
##
## These upgrade procedures are executed, regardless of current version
##########################################################################

# Check to make sure that the ibdata file has been split
pushd ./setup/upgrades
. "./000-fix-ibdata.sh"
popd

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

# Handle any necessary DB Schema migrations
php ./setup/db/migrate-db.php $(grep release= ./fusion/var/fusionversion | cut -d = -f 2)

# Fix perms on Backups (make backup directory if it doesn't exist)
if [ ! -d /store/backups/nagiosfusion ]; then

    echo "Creating backups directory..."
    mkdir -p /store/backups/nagiosfusion
    chown $nagiosuser:$nagiosgroup -R /store/backups/nagiosfusion
fi

# Update sudoers
if [ $UPDATE_SUDOERS -eq 1 ]; then

    echo "Updating sudoers file..."

    if [ -d "/etc/sudoers.d" ]; then

        cp /etc/sudoers.d/nagiosfusion "$BAKDIR/sudoers"
        cp ./setup/inc/sudoers /etc/sudoers.d/nagiosfusion
        chmod 440 /etc/sudoers.d/nagiosfusion

    else

        cp /etc/sudoers "$BAKDIR/etc.sudoers"
        grep -v NAGIOSFUSION /etc/sudoers > /etc/sudoers.new
        mv -f /etc/sudoers.new /etc/sudoers
        cat ./setup/inc/sudoers >> /etc/sudoers

    fi

    # Replace apache user with www-data for Ubuntu installs
    if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
        sed -i 's/=apache/=www-data/' /etc/sudoers
        sed -i 's/NAGIOSFUSIONWEB=apache/NAGIOSFUSIONWEB=www-data/' /etc/sudoers.d/nagiosfusion
    fi

    chmod 440 /etc/sudoers
fi

# Update cron
echo "Updating Fusion cronjobs..."
cp /etc/cron.d/nagiosfusion "$BAKDIR/cron.root"
cp ./setup/inc/cron.root /etc/cron.d/nagiosfusion

# Update logrotate
echo "Updating Fusion logrotate file..."
cp /etc/logrotate.d/nagiosfusion "$BAKDIR/logrotate"
cat ./setup/inc/logrotate | sed "s|PRODDIR|$proddir|" > /etc/logrotate.d/nagiosfusion

# Backup config before updating...
echo "Backing up current configuration..."
cp "$proddir/html/config.inc.php" "$BAKDIR/config.inc.php"

# Update Fusion files
echo "Updating Fusion files..."
tar czfp "$BAKDIR/nagiosfusion.tar.gz" /usr/local/nagiosfusion
cp -r ./fusion/* "$proddir"

chown -R "root:$nagiosgroup" "$proddir"
chown -R "$nagiosuser:$nagiosgroup" "$proddir/var"
chmod 775 "$proddir/var"
chmod 775 "$proddir/var/log"
chmod 755 "$proddir"
chown -R "$apacheuser:$nagiosgroup" "$proddir/tmp"
chmod -R 6775 "$proddir/tmp"

# Ensure sudoers scripts are owned by root
for script in "upgrade_to_latest.sh" "change_timezone.sh" "manage_services.sh" "utils.sh" "import_fusionconfig.php"
do
    chown "root:$nagiosgroup" "$proddir/scripts/$script"
    chmod 554 "$proddir/scripts/$script"
done

# Restore config after updating...
echo "Restoring existing configuration..."
cp "$proddir/html/config.inc.php" "$proddir/html/config.inc.php.dist"
cp "$BAKDIR/config.inc.php" "$proddir/html/config.inc.php"

# Restart services
echo "Restarting apache.."
$proddir/scripts/manage_services.sh restart $httpd
echo "Restarting mysql.."
$proddir/scripts/manage_services.sh restart mysqld
echo "Restarting crond.."
$proddir/scripts/manage_services.sh restart $crond

if [ $ver -eq 7 ] || [ $ver -eq 8 ] || [ $ver -eq 9 ] || [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
    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
else
    ip=$(ifconfig | egrep -1 eth[0-9] | grep -m 1 'inet' | awk '/inet[^6]/{print substr($2,6)}')

        if [ "$ip" == "" ]; then
            ip=$(ifconfig | egrep -1 eth[0-9] | grep -m 1 'inet' | awk '/inet6/{print substr($2,6)}')
            ip="[$ip]"
        fi
fi

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

{
cat <<-EOF

    Nagios Fusion Upgrade Complete!
    -------------------------------
    A complete backup of important system files can be found at
        $BAKDIR

    You can access the Nagios Fusion web interface by visiting:
        http://$ip/nagiosfusion/
    
EOF
} | tee -a "$log"
