#!/bin/bash -e

# Product Release 400 was the Fusion4 Technical Preview
# Since 0301.sh checks for versions prior to
# 2014r1.1, this is the upgrade portion specifically for
# Nagios Fusion 2014 R1.1
# Note: If this upgrade is ran, then 4000.sh does not
#   need to be ran - so we update the $oldversion
#   variable before we exit
if [ "$oldversion" -eq 301 ]; then

    echo "Detected Fusion version 2014r1.1. Proceeding with upgrade..."

    if [ "$INTERACTIVE" = "True" ]; then

        echo "WARNING!"
        echo "Continuing with this upgrade will remove all data. We will attempt to backup and import users and fused servers."
        echo ""
        echo "ALL DATA WILL BE LOST: DASHBOARDS, DASHLETS, COMPONENTS, CUSTOM FUNCTIONALITY!"
        echo "We will *ATTEMPT* to backup and import users and fused servers."
        echo ""
        echo "ALL USERS IMPORTED WILL BE ADMINISTRATORS ONCE THE UPGRADE IS COMPLETE"
        echo "ALL OF THE SERVERS WILL IMMEDIATELY BEGIN POLLING"
        echo ""
        echo "ALL CUSTOM FUNCTIONALITY AND DATA WILL BE LOST!"
        read -p "Do you want to continue? [Y/n] " res    

        case "$res" in
            Y | y | "")
                echo "Proceeding with upgrade..."
                ;;
            *)
                echo "Upgrade cancelled"
                exit 1
        esac
    fi

    # backup nagiosfusion directory and remove it so installation can occur cleanly
    echo "Backing up 2014r1.1 fusion to $BAKDIR and removing fusion directory"
    tar czfp "$BAKDIR/2014nagiosfusion.tar.gz" /usr/local/nagiosfusion
    rm -rf /usr/local/nagiosfusion/*

    # Database pre-initialization
    {
    echo "Checking MySQL credentials..."

    # Check Mysql root password if MySQL is already installed and running...
    if service $mysqld status &>/dev/null; then
        # Test for null MySQL root password
        if mysqlshow -u root &>/dev/null; then
            echo "After installation your MySQL root password will be set to 'fusion' (without quotes)."
        elif mysqlshow -u root -p"$mysqlpass" &>/dev/null; then
            echo "Stored MySQL password validated."
        else
            for i in 1 2 3; do
                if [ "$INTERACTIVE" = "True" ]; then
                    echo "Enter the MySQL root password to continue..."
                    read -p "MySQL Root Password: " pass
                fi

                # Test the password
                if mysqlshow -u root -p"$pass" &>/dev/null; then
                    echo "Password validated."
                    mysqlpass="$pass"

                    # Update fusion-sys.cfg with MySQL password for later use
                    if ! setvar mysqlpass "$mysqlpass"; then
                        echo "ERROR: Failed to update fusion-sys.cfg with MySQL password - exiting." >&2
                        exit 1
                    fi

                    break
                else
                    echo "Password failed." >&2
                    [ $i -eq 3 ] && exit 1
                fi
            done
        fi
    else
        echo "MySQL not yet installed - that's okay."
    fi
    } | tee -a "$log"

    # need to run the subs as if this was a fresh install..
    # don't worry, this upgrade will only be in here for the very first release of fusion4
    echo "Executing subs as if this were a full install.."
    pushd ./../
    run_sub ./00-repos.sh noupdate
    run_sub ./01-prereqs.sh
    run_sub ./02-usergroups.sh
    run_sub ./03-database.sh
    run_sub ./04-general.sh
    run_sub ./05-basedir.sh

    # We already ran this
    #run_sub ./06-sourceguardian.sh
    
    run_sub ./07-subsystem.sh
    run_sub ./08-security.sh
    run_sub ./09-finish.sh
    popd

    # Get config variables again..
    "$proddir/scripts/import_fusionconfig.php" > "config.dat"
    . "config.dat"
    rm "config.dat"

    # grab server and user data
    echo "\copy (SELECT * FROM fusion_options WHERE name = 'servers') To '/tmp/servers.csv' With CSV DELIMITER ','" > get_data.sql
    echo "\copy (SELECT * FROM fusion_options WHERE name = 'server_credentials') To '/tmp/credentials.csv' With CSV DELIMITER ','" >> get_data.sql
    echo "\copy (SELECT * FROM fusion_users) To '/tmp/users.csv' With CSV DELIMITER ','" >> get_data.sql
    psql -U nagiosfusion nagiosfusion < get_data.sql

    # update some of the files a bit..
    sed -i 's/^[0-9]*,servers,"//;s/"$//' /tmp/servers.csv
    sed -i 's/^[0-9]*,server_credentials,"//;s/"$//' /tmp/credentials.csv

    # we can convert the users file directly to sql
    cat /tmp/users.csv | awk -F, -v q="'" '{ print "INSERT INTO users (username, password, name, email, enabled, level) VALUES ("q $2 q", "q $3 q", "q $4 q", "q $5 q", " $7 ", 1);" }' > users.sql

    # insert users and servers
    echo "Re-Inserting existing users..."
    mysql -p$mysqlpass fusion < users.sql

    echo "Re-Inserting existing servers..."
    php 0400-servers.php

    # Updated successfully!
    # We don't need to run 3995.sh since it essentially
    # does the same thing that this script does
    oldversion=3995

    # force components to update
    export FORCE_ADDON_UPGRADE="True"
fi
