#!/usr/bin/env bash
# Copyright (c) 2016, Codership Oy. All rights reserved.
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

#
# A wsrep-enabled MySQL server daemon needs a special option if it is to start
# as the first node of a Galera cluster.
# With SystemV init, this could be passed as a "bootstrap" (rather than "start") command:
#     sudo service mysqld bootstrap
#
# With systemd, such alternative commands are not possible.
# However, systemd passes a set of environment variables to the service process
# it starts, and this set can be modified.
# Such a modification would be persistent, so it must be undone after use.
#
# If other options are set already, make sure to use them, and to restore them.

OLDVAL=$(systemctl show-environment | grep '^MYSQLD_OPTS=')

cleanup () {
    if [ -z "$OLDVAL" ]; then
        systemctl unset-environment MYSQLD_OPTS
    else
        systemctl set-environment "$OLDVAL"
    fi
}

trap cleanup EXIT

if [ -z "$OLDVAL" ]; then
    systemctl set-environment MYSQLD_OPTS="--wsrep-new-cluster"
else
    systemctl set-environment "$OLDVAL --wsrep-new-cluster"
fi

systemctl start ${1:-}
