#!/bin/bash
#
# Bash script for upgrading Nagios Network Analyzer
# Copyright 2014-2025 Nagios Enterprises, LLC. All Rights reserved.
#
# Upgrade Nagios Network Analyzer
#

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

PROD_DIR="/var/www/html/nagiosna"
BACKEND_DIR="/usr/local/nagiosna"
SCRIPTS_DIR="$BACKEND_DIR/scripts/"
NAVERSION_FILE="$PROD_DIR/naversion"
ARTISAN="$PROD_DIR/artisan"

if [ "x$INTERACTIVE" = "x" ]; then
    export INTERACTIVE="True"
fi

# Ensure the script is run as root
if [ $UID != 0 ] ; then
    echo_c "ERROR: This script must be run as root!" "$RED"
    exit 1
fi

upgrade_help() {
    cat <<-EOF

        Nagios Network Analyzer Upgrade Script
        Copyright 2025-, Nagios Enterprises LLC.
        License:
            Nagios Software License <http://assets.nagios.com/licenses/nagios_software_license.txt>

        Usage: ./upgrade [options...]

        Options:
            -h | --help
                Display this help text
            -n | --non-interactive
                Assume defaults for all questions (for scripted installs)
EOF
}

# Parse command line arguments
while [ -n "$1" ]; do
    case "$1" in
        -h | --help)
            upgrade_help
            exit 0
            ;;
        -n | --non-interactive)
            export INTERACTIVE="False"
            ;;
        *)
            echo "Unknown option:  $1"
            upgrade_help
            exit 1
            ;;
    esac
    shift
done

# Restart the upgrade
if [ -t 1 ]; then
    $0 2>&1 | tee >(sed -r 's/\x1B\[[0-9;]*m//g' >> "upgrade.log")
    exit 0
fi

# Interactive warning and confirmation unless -n was provided
if [ "$INTERACTIVE" = "True" ]; then
    echo_c "IMPORTANT: Before upgrading, verify you have a valid system backup of Nagios Network Analyzer before continuing! \
More information about backing up and restoring Nagios Network Analyzer can be found here: \
https://assets.nagios.com/downloads/nagios-network-analyzer/docs/Backing-Up-and-Restoring-NNA-2026.pdf" "$ORANGE" >&2
    echo
    echo_c "Are you sure you want to continue? [y/N]" "$GREEN"
    read res

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

# Get the old version
if [ ! -f "$NAVERSION_FILE" ]; then
    echo_c "ERROR: Could not determine currently installed version of Nagios Network Analyzer!" "$RED"
    exit 1
fi
OLD_VERSION="$(grep '^VERSION=' "$NAVERSION_FILE" | cut -d '=' -f2)"
old_version_full="$(grep '^full=' "$NAVERSION_FILE" | cut -d '=' -f2)"
new_version_full="$(grep '^full=' "$BASE_DIR/nagiosna/naversion" | cut -d '=' -f2)"

# Print upgrade header
echo
echo
echo "Upgrading Nagios Network Analyzer"
echo "================================="
echo "DATE: $(date)"
echo
echo "DISTRO INFO:"
echo "$distro"
echo "$version"
echo "$architecture"
echo
echo "Upgrading from $old_version_full to $new_version_full"
echo "================================="
echo

#### UPGRADE PREREQUISITES ####

# Verify the old version is at least 2026R1
if [ "$OLD_VERSION" -lt "500" ]; then
    echo_c "You are currently on a pre-2026R1 version of Nagios Network Analyzer. \
Please use the migration script to upgrade to NNA 2026R1. \
From there you can continue to upgrade to the latest version." "$RED"
    echo_c "For more information see the documentation at \
https://assets.nagios.com/downloads/nagios-network-analyzer/docs/Migrating-from-Network-Analyzer-2024-to-2026.pdf" "$RED"
    exit 1
fi

# Verify server has needed prereqs
cp "$BASE_DIR/nagiosna/app/Console/Commands/CheckPrereqsCommand.php" "$PROD_DIR/app/Console/Commands/CheckPrereqsCommand.php"
cp "$BASE_DIR/nagiosna/app/Services/MaintenanceService.php" "$PROD_DIR/app/Services/MaintenanceService.php"
if ! (php "$PROD_DIR/artisan" prereqs:check); then
    exit 1
fi

# Ensure Suricata is not running
if command -v suricata >/dev/null 2>&1; then
    suricata_bin=$(which suricata)
    suricata_pid=$(pgrep -u nna -f "$suricata_bin" 2>/dev/null | head -n 1)

    if [ -n "$suricata_pid" ]; then
        echo_c "ERROR: Suricata is currently running. Please stop Suricata via the web interface before upgrading." "$RED"
        exit 1
    fi
fi

# Ensure packages are installed
echo_c "Installing packages..." "$BLUE"
# shared_pkgs=""
# shared_python_pkgs=""

# if [[ "$distro" == "Ubuntu" || "$distro" == "Debian" ]]; then
#     pkgs=""
#     python_pkgs=""

#     apt-get -y update
#     apt -y install $shared_pkgs $pkgs
#     apt -y install $shared_python_pkgs $python_pkgs
# else
#     pkgs=""
#     python_pkgs=""

#     dnf -y update
#     dnf -y install $shared_pkgs $pkgs
#     dnf -y install $shared_python_pkgs $python_pkgs
# fi

# Upgrade sourceguardian loader
echo_c "Upgrading SourceGuardian loader..." "$BLUE"
install_sourceguardian
if [ `command -v systemctl` ]; then
    systemctl restart $httpd
else
    service $httpd restart
fi


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

# Backup the .env file
cp "$PROD_DIR/.env" /tmp/.nagiosna.env.backup
if [ ! -f /tmp/.nagiosna.env.backup ]; then
    echo_c "Failed to backup .env file!" "$RED"
    exit 1
fi

# Copy new application files
echo_c "Copying new application files..." "$BLUE"
cp -rf "$BASE_DIR"/mibs/* "$mibsdir"
cp -rf "$BASE_DIR"/scripts/* "$SCRIPTS_DIR"
cp -rf "$BASE_DIR"/nagiosna/* "$PROD_DIR"

# Restore the .env file
cp /tmp/.nagiosna.env.backup "$PROD_DIR/.env"

# Run DB migrations
echo_c "Running database migrations..." "$BLUE"
php "$ARTISAN" migrate --force

# Permissions for Laravel directories
echo_c "Setting up permissions..." "$BLUE"
chown -R "$apacheuser":nnacmd "$PROD_DIR/storage" "$PROD_DIR/bootstrap/cache"
chmod -R 0775 "$PROD_DIR/storage"
chmod -R 0775 "$PROD_DIR/bootstrap/cache"

# Permissions for logs
chown "$apacheuser":nnacmd "$PROD_DIR/storage/logs"
chmod 2775 "$PROD_DIR/storage/logs"
touch "$PROD_DIR/storage/logs/cron.log"
chown nna:nnacmd "$PROD_DIR/storage/logs/cron.log"
chmod 664 "$PROD_DIR/storage/logs/cron.log"

# Permissions for backend directories
chown -R nna:nnacmd "$BACKEND_DIR"
chmod -R 0775 "$BACKEND_DIR"
chown root:nnacmd "$BACKEND_DIR/scripts"
chmod 0755 "$BACKEND_DIR/scripts"

# Copy sudoers file over
if [ -d /etc/sudoers.d/ ]; then
    cp -f "$BASE_DIR/nagiosna.sudoers" /etc/sudoers.d/nagiosna
else
    # Remove old sudoers entries
    grep -v 'Defaults:%nnacmd' /etc/sudoers > /etc/sudoers.new
    mv -f /etc/sudoers.new /etc/sudoers

    # Add new sudoers entries
    cat "$BASE_DIR/nagiosna.sudoers" >> /etc/sudoers
    chmod 440 /etc/sudoers
fi

# Restart services
echo_c "Restarting services..." "$BLUE"
supervisorctl restart all || echo_c "Warning: Some worker processes may have exited abnormally, continuing..." "$ORANGE"


#### VERSION SPECIFIC UPDATES ####

# NA 2026R1.0.1
if [ "$OLD_VERSION" -lt "501" ]; then
    sed -i "s|^\s*ServerName .*|    ServerName $(hostname -I | awk '{print $1}')|" "${httpdconfdir}/nna.conf"
    php "$ARTISAN" db:seed --force --class=_2026R1_0_1_Seeder
fi


### PRINT COMPLETION BANNER ###

IP_ADDRESS="$(hostname -I | awk '{print $1}')"
URL="http://$IP_ADDRESS"
URL_LENGTH=${#URL}
INNER_WIDTH=52
TOTAL_PADDING=$((INNER_WIDTH - URL_LENGTH))
LEFT_PADDING=$((TOTAL_PADDING / 2))
RIGHT_PADDING=$((TOTAL_PADDING - LEFT_PADDING))

echo
echo_c "######################################################" "$CYAN"
echo_c "#                                                    #" "$CYAN"
echo_c "#      Nagios Network Analyzer Upgrade Complete!     #" "$CYAN"
echo_c "#                                                    #" "$CYAN"
echo_c "# -------------------------------------------------- #" "$CYAN"
echo_c "#                                                    #" "$CYAN"
echo_c "#       Access the web interface by visiting:        #" "$CYAN"
printf "${CYAN}#${NC}%*s${BLUE}%s${NC}%*s${CYAN}#${NC}\n" \
    "$LEFT_PADDING" "" "$URL" "$RIGHT_PADDING" ""
echo_c "#                                                    #" "$CYAN"
echo_c "######################################################" "$CYAN"
echo
