#!/bin/bash -e

# Technical Preview
if [ "$oldversion" -eq 400 ]; then

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

        echo "Continuing with this upgrade will remove all existing polled data and dashboards."
        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

    # make sure version file is right
    if [ -f $proddir/var/version ]; then

        echo "Copying old fusion version file..."
        mv $proddir/var/version $proddir/var/fusionverson
    fi

    # stop cron
    echo "Shutting down cron..."
    $proddir/scripts/manage_services.sh stop $crond

    # kill existing cron jobs
    echo "Killing existing Fusion cronjobs..."
    ps aux | grep php | grep fusion | grep cron | awk '{ print $2 }' | xargs kill

    # backup the existing data
    echo "Backing up existing data..."
    mysqldump -h $cfg__database__fusion__host -u $cfg__database__fusion__user --password="$cfg__database__fusion__pass" $cfg__database__fusion__dbname meta options servers users users_servers > backup.sql

    # drop all tables from fusion db
    echo "Destroying old database..."
    cat ../db/schemas/fusion.sql | grep "CREATE TABLE" | sed 's/.*`fusion`.`//' | sed 's/`.*//' | sed 's/.*/DROP TABLE IF EXISTS &;/' > drop_tables.sql
    mysql -h $cfg__database__fusion__host -u $cfg__database__fusion__user --password="$cfg__database__fusion__pass" $cfg__database__fusion__dbname < drop_tables.sql

    # recreate all tables with newest schema
    echo "Recreating database with latest schema..."
    cat ../db/schemas/fusion.sql | grep -v "CREATE DATABASE" | grep -v "CREATE USER" | grep -v "GRANT ALL" > new_schema.sql
    mysql -h $cfg__database__fusion__host -u $cfg__database__fusion__user --password="$cfg__database__fusion__pass" $cfg__database__fusion__dbname < new_schema.sql

    # return data to the db
    echo "Replacing data into database..."
    mysql -h $cfg__database__fusion__host -u $cfg__database__fusion__user --password="$cfg__database__fusion__pass" $cfg__database__fusion__dbname < backup.sql

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