#!/bin/bash

# Check for existence of the mysql conf file
mysqlconf="/etc/my.cnf"
if [ ! -f "$mysqlconf" ]; then
    mysqlconf="/etc/mysql/my.cnf"
fi

# Update/add the innodb_file_per_table directive in the mysql conf file
if grep -Fq "innodb_file_per_table" "$mysqlconf"; then

    # Replace the directive with a value of 1
    echo "Updating innodb_file_per_table in $mysqlconf..."
    sed -i "s/innodb_file_per_table.*/innodb_file_per_table = 1/" "$mysqlconf"
else

    # Append the directive below [mysqld] 
    echo "Adding innodb_file_per_table in $mysqlconf..."
    sed -i '/\[mysqld\]/a innodb_file_per_table = 1' "$mysqlconf"
fi

# Check if Fusion db exists and is already broken into multiple files
if [ -d /var/lib/mysql/fusion ] && [ -f /var/lib/mysql/fusion/users.ibd ]; then
    echo "Fusion files already broken into ibd files, skipping"
    return 0
fi

# We need to fix the giant ibdata1 file
# So, in order to do that - we do a fusion db backup
# But we also need to backup any other databases that
# may have been created as a precaution

origmysqlpass="$mysqlpass"

# We need to test if the mysqlpass (root pass)
# we have is going to be usable, otherwise we need to prompt the user
# for a new root password
if [ "$mysqlpass" = "" ]; then
    mysqlpass="fusion"
fi

# Check the password we already have
if mysqlshow -u root -p"$mysqlpass" &>/dev/null; then

    echo "Stored root mysql password is good to go..."

# Test for null MySQL root password
elif mysqlshow -u root &>/dev/null; then

    # Set the password to "fusion"
    mysqlpass=fusion  
    mysqladmin -u root password "$mysqlpass"
    echo "MySQL root password is now set to: $mysqlpass"

# Get the password
else
    for i in 1 2 3; do
        # Ask for the password
        echo "Enter the MySQL root password to continue..."
        read -p "MySQL Root Password: " pass

        # Test the password
        if mysqlshow -u root -p"$pass" &>/dev/null; then
            echo "Password validated."
            mysqlpass="$pass"
            break
        else
            echo "Password failed." >&2
            [ $i -eq 3 ] && exit 1
        fi
    done
fi

# Update the password if it failed
if [ "$origmysqlpass" != "$mysqlpass" ]; then
    pushd ../
        if ! ./set-fusion-var.sh mysqlpass "$mysqlpass"; then
            echo "Updating mysqlpass failed, continuing with database maintenance"
        fi
    popd
fi

# Check if we get our list of databases
dbs=$(mysql -u root -p"$mysqlpass" --skip-column-names --batch -e 'show databases')
ret=$?
if [ $ret -ne 0 ]; then
    echo "Unable to grab database names, skipping maintenance"
    return 0
fi

errors="False"

# We keep the list in databases, and the sql files in databasebackups
mkdir databasebackups
touch databases

# Stop a user from Ctrl+C during this process
echo "WARNING: Do NOT interupt the upgrade script during this process"
trap '' SIGINT

echo "============================================"
echo "Backing up databases"
echo "============================================"

# Loop through databases and back up data
for db in $dbs
do

    if [ "$db" = "performance_schema" ] || [ "$db" = "information_schema" ] || [ "$db" = "mysql" ] || [ "$db" = "test" ]; then
        echo "Skipping db: $db"
        continue
    fi

    echo "$db" >> databases
    echo "Backing up $db..."

    if ! mysqldump -u root -p"$mysqlpass" $db >databasebackups/$db; then
        echo "SOMETHING WENT WRONG BACKING UP $db"
        errors="True"
    fi
done

# If we got an error here, stop attempting and close out
if [ "$errors" = "True" ]; then

    echo "An error occured while trying to backup your databases"
    echo "while the upgrade script was attempting to recover your"
    echo "ibdata1 file"
    echo ""
    echo "The manual process for this includes:"
    echo " * Backing up each of your databases into a sql file"
    echo "   - EXCEPT FOR 'information_schema'"
    echo "   - EXCEPT FOR 'performance_schema'"
    echo "   - EXCEPT FOR 'mysql'"
    echo " * Dropping the databases"
    echo "   - EXCEPT FOR 'information_schema'"
    echo "   - EXCEPT FOR 'performance_schema'"
    echo "   - EXCEPT FOR 'mysql'"
    echo " * Stopping the $mysqld service"
    echo " * Deleting the /var/lib/mysql/ibdata1 file"
    echo " * Starting the mysql/mariadb service"
    echo " * Creating the databases that were previously dropped"
    echo " * Restoring the data into the databases"
    echo ""
    echo "This script attempted to automate those steps, and"
    echo "and failed during the backup step - so it will not"
    echo "continue"

    rm databases
    rm -r databasebackups

    exit 0
fi

echo "============================================"
echo "Dropping databases"
echo "============================================"

# Loop through databases and drop the ones we need to drop
for db in $dbs
do

        if [ "$db" = "performance_schema" ] || [ "$db" = "information_schema" ] || [ "$db" = "mysql" ] || [ "$db" = "test" ]; then
                echo "Skipping db: $db"
                continue
        fi

    echo "Dropping database $db"
    mysql -u root -p"$mysqlpass" -e "drop database $db"

done

# Stop mysql
"$proddir/scripts/manage_services.sh" stop mysqld

# Delete the ibdata file
if ! rm /var/lib/mysql/ibdata1; then
    echo "Unable to delete ibdata1!"
fi
if ! rm /var/lib/mysql/ib_log*; then
    echo "Unable to delete ib_log files!"
fi

# Start mysql
"$proddir/scripts/manage_services.sh" start mysqld

echo "============================================"
echo "Restoring databases"
echo "============================================"

# Loop through the databases and restore them
dbs=$(cat databases)
for db in $dbs
do
    echo "Restoring $db..."

    mysql -u root -p"$mysqlpass" -e "create database $db"

    if ! mysql -u root -p"$mysqlpass" "$db" < databasebackups/$db; then
        echo "SOMETHING WENT WRONG RESTORING $db"
        errors="True"
    fi
done

# Restore SIGINT
trap SIGINT