#!/bin/bash

# Install controller base required packages

set -eu
set -o xtrace
set -o pipefail

DISTRO=`lsb_release -si` || true

if [[ "Ubuntu Debian" =~ "$DISTRO" ]]; then
    install-packages percona-xtrabackup \
        percona-xtradb-cluster-common-5.5 percona-xtradb-cluster-server-5.5 \
        percona-xtradb-cluster-client-5.5 percona-xtradb-cluster-galera-2.x
elif [[ "RedHatEnterpriseServer CentOS Fedora" =~ "$DISTRO" ]]; then
    echo "Please use mariadb on RedHat, CentOS or Fedora systems"
    exit 1
else
    echo "05-mysql should have failed before this"
    exit 1
fi

sed -i -e 's,^datadir=$,datadir=/mnt/state/var/lib/mysql,' /etc/init.d/mysql
sed -i -e 's,mysql_data_dir="/var/lib/mysql",mysql_data_dir="/mnt/state/var/lib/mysql",' /etc/init.d/mysql

# The following line are due to a bug found in the Percona supplied init
# script where the start sequence does not capture and return an error
# code. See https://bugs.launchpad.net/percona-xtradb-cluster/+bug/1339894
# Percona has committed but not yet released this fix.
if ! grep -q 'if \! $0 start $other_args; then' /etc/init.d/mysql; then
    sed -ie 's/$0 start $other_args$/if \! $0 start $other_args; then\n        exit 1\n      fi/' /etc/init.d/mysql
else
    echo "WARNING: https://review.openstack.org/#/c/104569/ should be reverted if"
    echo "WARNING: https://bugs.launchpad.net/percona-xtradb-cluster/+bug/1339894"
    echo "WARNING: has been released, and the project has been updated to make"
    echo "WARNING: use of the updated percona-xtradb-cluster release."
fi

# Templates write the configs into /mnt/state. However, MySQL makes it very
# difficult not to use this as the directory for configs.
rm -rf /etc/mysql
ln -s /mnt/state/etc/mysql /etc/mysql

if [ -e /etc/apparmor.d/usr.sbin.mysqld ] ; then
    sed -i -e 's,/var/lib/mysql/,/mnt/state/var/lib/mysql/,g' /etc/apparmor.d/usr.sbin.mysqld
    sed -i -e 's,/var/log/mysql/,/mnt/state/var/log/mysql/,g' /etc/apparmor.d/usr.sbin.mysqld
    sed -i -e 's,/etc/mysql/,/mnt/state/etc/mysql/,g' /etc/apparmor.d/usr.sbin.mysqld
fi

if [ -e /etc/init/mysql.conf ]; then
    sed -i -e 's,/var/lib/mysql/,/mnt/state/var/lib/mysql/,g' /etc/init/mysql.conf
fi

# The packages create a initial db which we don't want or need
rm -fr /var/lib/mysql

# We need to setup the directory with appropriate permissions and then
# the first time we boot a particular state partition we rsync this in.
[ -d /var/log/mysql ] || install -d -o root -g mysql -m 0775 /var/log/mysql
register-state-path --leave-symlink /var/log/mysql

# galera lib path is set in mysql config file, creating symlink
# /usr/local/mysql/lib/libgalera_smm.so allows us to use same path
# for mysql and mariadb and for i386/amd64
[ -e /usr/local/mysql/lib ] || install -m 0755 -o root -g root -d /usr/local/mysql/lib
ln -sf /usr/lib/libgalera_smm.so /usr/local/mysql/lib/libgalera_smm.so
