#!/bin/bash

# Copyright (c) 2015, 2017, Oracle and/or its affiliates. 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, version 2.0,
# as published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# but not limited to OpenSSL) that is licensed under separate terms,
# as designated in a particular file or component or in included license
# documentation.  The authors of MySQL hereby grant you an additional
# permission to link the program and your derivative works with the
# separately licensed software that they have included with MySQL.
#
# 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, version 2.0, 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

# Script modified to handle the specific needs of the "wsrep" plugin
# which enables a MySQL server to act as a node in Galera Cluster.
# Modifications
# Copyright (c) 2015, 2016, Codership Oy

# Scripts to run by MySQL systemd service
#
# Needed argument: pre | post
#
# pre mode  :  try to perform sanity check for configuration, log, data
# post mode :  ping server until answer is received


# Include helper functions
. /usr/share/mysql/mysql-helpers

sanity () {
	if [ ! -r /etc/mysql/my.cnf ]; then
                systemd-cat -t mysql -p err \
		        echo "MySQL configuration not found at /etc/mysql/my.cnf. Please install one using update-alternatives."
		exit 1
	fi

# Make sure database and required directories exist
	verify_ready
	verify_database

	@DEB_INIT_APPARMOR@
}

pinger () {
    server_up=false
    for i in $(seq 1 30); do
        sleep 1
        if mysqladmin ping >/dev/null 2>&1; then
            server_up=true
            break
        fi
    done
    clear_recover_pos
    if [ ! $server_up ]; then
        systemd-cat -t mysql -p err \
            echo "MySQL server not started"
        exit 1
    fi
}

case $1 in
	"pre")  sanity ;;
        "post") pinger ;;
esac
