#!/bin/bash
set -eu

MYSQL_INITIALIZED="/mnt/state/var/lib/mysql/galera.initialized"

pid_path=/var/run/mysqld/mysqld.pid
mkdir -p $(dirname $pid_path)
chown mysql:root $(dirname $pid_path)

if [ ! -e ${MYSQL_INITIALIZED} ]; then
    if os-is-bootstrap-host; then
        # Needed to setup initial tables. This command is idempotent.
        /usr/local/mysql/scripts/mysql_install_db --user=mysql --basedir=/usr/local/mysql --datadir=/mnt/state/var/lib/mysql --no-defaults --pid-file=$pid_path  --wsrep-new-cluster

        # We install this init script so we can trust this path exists.
        # Use of restart-bootstrap vs bootstrap-pxc ensures that, even if
        # MySQL is running, the bootstrap will succeed.
        /etc/init.d/mysql restart-bootstrap
    elif [ $? -eq 1 ]; then
        if grep -qE '^wsrep_cluster_address[[:space:]]*=[[:space:]]*gcomm://[[:space:]]*$' /etc/mysql/conf.d/cluster.cnf; then
            echo "We are configured as joiner and have no nodes configured for the cluster. Refusing to proceed until cluster nodes are known."
            exit 1
        fi

        os-svc-restart -n mysql
    else
        echo "We are neither cluster initializer or joiner. Refusing to bootstrap mysql cluster until role is known."
        exit 1
    fi

    # Ensure we actually have a working database, the Percona init script does not
    # always exit with a non zero code upon failure.
    if [ ! -S /var/run/mysqld/mysqld.sock ]; then
        echo "MySQL Socket missing, is percona running correctly?"
        exit 1
    fi

    # Finally, perform a MySQL "ping". This will succeed even when MySQL returns
    # an "Access Denied" packet, avoiding the need to provide valid credentials.
    /usr/local/mysql/bin/mysqladmin ping

    touch ${MYSQL_INITIALIZED}
else
    # For single node setups we can re-bootstrap if were not currently running
    # We need to ensure we are bootstrap host to prevent our regex succeeding
    # in case mysql.hosts comes in piecemeal
    LOCAL_IP=$(os-apply-config --key local-ipv4 --type netaddress --key-default '')
    if os-is-bootstrap-host && grep -Eq "^wsrep_cluster_address=gcomm://$LOCAL_IP,?\$" /etc/mysql/conf.d/cluster.cnf; then
        if ! /etc/init.d/mysql status; then
            /etc/init.d/mysql restart-bootstrap
        fi
    fi
fi

os-svc-enable -n mysql
