#!/bin/bash -e
#
# Upgrades Nagios Fusion to the Latest Version
# Copyright (c) 2018 Nagios Enterprises, LLC. All rights reserved.
#

PATH=$PATH:/sbin:/usr/sbin
TS=$(date +%s)
error=false
BASEDIR=$(dirname $(readlink -f $0))

# Import Nagios Fusion and fusion-sys.cfg config vars
#. $BASEDIR/../var/fusion-sys.cfg
. $BASEDIR/utils.sh
nagios_source_vars $BASEDIR/../var/fusion-sys.cfg
eval $(php $BASEDIR/import_fusionconfig.php)

###############################
# USAGE / HELP
###############################
function usage () {
    echo ""
    echo "Use this script to upgrade your Nagios Fusion instance to the latest version."
    echo ""
    echo " -t | --time      Send a timestamp for the log to be renamed as once finished"
    echo " -h | --help      Help usage information"
    echo ""
}

###############################
# GET THE VARIABLES
###############################
while [ -n "$1" ]; do
    case "$1" in
        -h | --help)
            usage
            exit 0
            ;;
        -t | --time)
            TS=$2
            ;;
    esac
    shift
done

# Create a log file
rm -rf /usr/local/nagiosfusion/tmp/upgrade.log
touch /usr/local/nagiosfusion/tmp/upgrade.log
chown $nagiosuser:$nagiosgroup /usr/local/nagiosfusion/tmp/upgrade.log

# Backup Fusion before upgrade
echo "---- Starting Nagios Fusion Backup ----" > /usr/local/nagiosfusion/tmp/upgrade.log
cd /usr/local/nagiosfusion/scripts
./backup_fusion.sh -p autoupgrade_backup >> /usr/local/nagiosfusion/tmp/upgrade.log 2>&1

# Perform upgrade
echo "" >> /usr/local/nagiosfusion/tmp/upgrade.log
echo "---- Starting Nagios Fusion Upgrade ----" >> /usr/local/nagiosfusion/tmp/upgrade.log
echo "Cleaning up temp directory..." >> /usr/local/nagiosfusion/tmp/upgrade.log
cd /usr/local/nagiosfusion/tmp
rm -rf nagiosfusion
if [ -f fusion-latest.tar.gz ]; then
    tar xzf fusion-latest.tar.gz
else
    tar xzf nagiosfusion-*.tar.gz
fi
cd nagiosfusion
echo "Starting upgrade..."

./upgrade -n >> /usr/local/nagiosfusion/tmp/upgrade.log 2>&1
if [ $? -ne 0 ]; then
    FN="failed.$TS"
else
    FN="success.$TS"
fi

# Make log directory if it doesnt exist and give proper permissions for apache to be able to read it
if [ ! -d /usr/local/nagiosfusion/var/upgrades ]; then
    mkdir -p /usr/local/nagiosfusion/var/upgrades
    chown $apacheuser:$nagiosgroup /usr/local/nagiosfusion/var/upgrades
    chmod 754 /usr/local/nagiosfusion/var/upgrades
    chmod +x /usr/local/nagiosfusion/var/upgrades
fi

# Copy over the file and give error or not
cp /usr/local/nagiosfusion/tmp/upgrade.log /usr/local/nagiosfusion/var/upgrades/$FN.log
chown -R $apacheuser:$nagiosgroup /usr/local/nagiosfusion/var/upgrades
chmod 644 /usr/local/nagiosfusion/var/upgrades/$FN.log

# Clean up tmp directory
cd /usr/local/nagiosfusion/tmp
rm -rf nagiosfusion fusion-*.tar.gz nagiosfusion-*.tar.gz
