#!/usr/bin/env bash

######################################
#     Install MySQL Server 5.5       #
# Created : 2013.03.18               #
# Creater : Nalee Jang               #
######################################

# Keep track of the devstack directory
TOP_DIR=$(cd $(dirname "$0") && pwd)

# Settings
# ========

MYSQL_HOST=${MYSQL_HOST:-localhost}
MYSQL_USER=${MYSQL_USER:-root}
MYSQL_PASSWORD=${MYSQL_PASSWORD:-superscrete}

# Install MySQL
# ================

echo "Install MySQL"

# Seed configuration with mysql password so that apt-get install doesn't
# prompt us for a password upon install.
cat <<MYSQL_PRESEED | sudo debconf-set-selections
mysql-server-5.1 mysql-server/root_password password $MYSQL_PASSWORD
mysql-server-5.1 mysql-server/root_password_again password $MYSQL_PASSWORD
mysql-server-5.1 mysql-server/start_on_boot boolean true
MYSQL_PRESEED

# while ``.my.cnf`` is not needed for OpenStack to function, it is useful
# as it allows you to access the mysql databases via ``mysql nova`` instead
# of having to specify the username/password each time.
if [[ ! -e $HOME/.my.cnf ]]; then
    cat <<EOF >$HOME/.my.cnf
[client]
user=$MYSQL_USER
password=$MYSQL_PASSWORD
host=$MYSQL_HOST
EOF
    chmod 0600 $HOME/.my.cnf
fi

# Install mysql-server
sudo apt-get update
sudo apt-get install mysql-server

# Configuring Mysql
# ==================

echo "Configuring and starting MySQL"

MY_CONF=/etc/mysql/my.cnf
MYSQL=mysql

# Update the DB to give user $MYSQL_USER full control of the all databases:
sudo mysql -uroot -p$MYSQL_PASSWORD -h127.0.0.1 -e "GRANT ALL PRIVILEGES ON *.* TO '$MYSQL_USER'@'%' identified by '$MYSQL_PASSWORD';"

# Now update ``my.cnf`` for some local needs and restart the mysql service

# Change bind-address from localhost (127.0.0.1) to any (0.0.0.0)
sudo sed -i '/^bind-address/s/127.0.0.1/0.0.0.0/g' $MY_CONF

# Set default db type to InnoDB
if sudo grep -q "default-storage-engine" $MY_CONF; then
    # Change it
    sudo bash -c "source $TOP_DIR/functions; iniset $MY_CONF mysqld default-storage-engine InnoDB"
else
    # Add it
    sudo sed -i -e "/^\[mysqld\]/ a \
default-storage-engine = InnoDB" $MY_CONF
fi

# Restart MySQL
echo "Restring MySQL"
sudo /usr/sbin/service mysql restart

echo "Done Install MySQL"
