#!/bin/sh
#----------------------------------------------------------------------------
# /etc/init.d/mariadb100 - eisfair MariaDB startup for eisfair-1
#
# Creation:     2006-06-07 jv
# Last Update:  $Id$
#
# Copyright (c) 2004-2010 Jens Vehlhaber, jens(at)eisfair(dot)org
# Copyright (c) 2011-@@YEAR@@ Holger Bruenjes, holgerbruenjes(at)gmx(dot)net
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#----------------------------------------------------------------------------

. /etc/init.d/functions

# Set the default values
# priority can be overriden and "-s" adds output to stderr
ERR_LOGGER="logger -p daemon.err -t /etc/init.d/mariadb100 -i"

# start/stop and failure message color output
COLOR_RED='\033[1;31m'
COLOR_NRM='\033[0;39m'

my_path=100
my_version=10.0

# ---------------------------------------------------------------------------
# usage
# ---------------------------------------------------------------------------
usage()
{
cat <<EOF

 Usage:
 ${0}
                -q, --quiet      suppress all normal output
                --skip           with mysql_upgrade
                [start]
                [stop]
                [status]
                [restart]

EOF

}

log_end_msg()
{
    if [ ${1} -eq 0 ]
    then
        echo_ok
    else
        echo_failure
    fi
}

log_failure_msg()
{
    echo -e " ${COLOR_RED}*${COLOR_NRM} $@"
}

parse_arguments()
{
    for arg do
        case "${arg}" in
        --basedir=*)   mysql_basedir="$(echo "${arg}"   | sed -e 's/^[^=]*=//')/bin" ;;
        --datadir=*)   mysql_datadir="$(echo "${arg}"   | sed -e 's/^[^=]*=//')" ;;
        --pid-file=*)  mysql_pid_file="$(echo "${arg}"  | sed -e 's/^[^=]*=//')" ;;
        --socket=*)    mysql_socket="$(echo "${arg}"    | sed -e 's/^[^=]*=//')" ;;
        --log-error=*) mysql_log_error="$(echo "${arg}" | sed -e 's/^[^=]*=//')" ;;
        --port=*)      mysql_port="$(echo "${arg}"      | sed -e 's/^[^=]*=//')" ;;
        esac
    done
}

parse_arguments $(/usr/lib/mysql/${my_path}/bin/my_print_defaults mysqld --defaults-file=/etc/mysql/my${my_path}.cnf)

# Do some sanity checks before even trying to start mysqld.
sanity_checks()
{
    # check for buggy options
    if /usr/bin/grep -q ^expire.logs.days /etc/mysql/my${my_path}.cnf  &&
     ! /usr/bin/grep -q ^log.bin /etc/mysql/my${my_path}.cnf
    then
        log_failure_msg "MariaDB ERROR: Using expire_logs_days without log_bin crashes the server."
        echo                    "ERROR: Using expire_logs_days without log_bin crashes the server." | $ERR_LOGGER
        exit 1
    fi

    # check for diskspace shortage
    if LC_ALL=C BLOCKSIZE= /usr/bin/df --portability "${mysql_datadir:-/srv/mysql/${my_path}}" . | /usr/bin/tail -n 1 | /usr/bin/awk '{ exit ($4>4096) }'
    then
        log_failure_msg "MariaDB ERROR: The partition with "${mysql_datadir:-/srv/mysql/${my_path}}" is too full!"
        echo                    "ERROR: The partition with "${mysql_datadir:-/srv/mysql/${my_path}}" is too full!" | $ERR_LOGGER
        exit 1
    fi
}


# wait if create/remove pid files
wait_for_pid()
{
    for COUNT in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
    do
        case "$1" in
        'created')
            test -s ${mysql_pid_file} && break
            ;;
        'removed')
            test ! -s ${mysql_pid_file} && break
            ;;
        esac
        sleep 1
        echo -n '.'
    done
    echo
    if [ ${COUNT} -gt 24 ]
    then
        log_end_msg 1
    else
        log_end_msg 0
        return 0
    fi
}


# Safeguard (relative paths, core dumps..)

# ---------------------------------------------------------------------------
# start
# ---------------------------------------------------------------------------
mariadb_start()
{
    # check for update without database upgrade
    if [ -f "/srv/mysql/${my_path}/update-install" ]
    then
        log_failure_msg 'MariaDB ERROR: Please run mariadb config'
        echo            'MariaDB ERROR: Please run mariadb config' | ${ERR_LOGGER}
        exit 1
    fi

    /usr/bin/mkdir -p -m 0755 /run/mysql
    /usr/bin/chown mysql:mysql /run/mysql

    if [ ! -f ${mysql_pid_file} ]
    then
        sanity_checks;
        boot_mesg -n  " * Starting MariaDB/MySQL database server ${my_version} "
        /usr/lib/mysql/${my_path}/bin/mysqld_safe \
               --defaults-file=/etc/mysql/my${my_path}.cnf \
               ${skip} >/dev/null 2>&1 &
        wait_for_pid created

        if [ ${?} -eq 0 ] &&
           [ ${mysql_port:-0} = 3306 ]
        then
            cd /run/mysql
            ln -sf ${my_path}/mysql.sock
        fi
    else
        boot_mesg " * MariaDB/MySQL database server ${my_version} is already running ..."
        echo_warning
    fi
}

# ---------------------------------------------------------------------------
# stop
# ---------------------------------------------------------------------------
mariadb_stop()
{
    # Stop daemon. We use a signal here to avoid having to know the
    # root password.
    if [ -f ${mysql_pid_file:-0} ]
    then
        boot_mesg -n  " * Stopping MariaDB/MySQL database server ${my_version} "
        mysqld_pid=$(/usr/bin/cat ${mysql_pid_file})
        kill ${mysqld_pid} &>/dev/null
        wait_for_pid removed
    else
        boot_mesg " * MariaDB/MySQL database server ${my_version} is not running"
        echo_warning
    fi
}

# ---------------------------------------------------------------------------
# restrat
# ---------------------------------------------------------------------------
mariadb_restart()
{
        mariadb_stop
        sleep 3
        mariadb_start
}

# ---------------------------------------------------------------------------
# status
# ---------------------------------------------------------------------------
mariadb_status()
{
    if [ ! -f ${mysql_pid_file} ]
    then
        boot_mesg " * MariaDB/MySQL server ${my_version} is not running"
        echo_warning
    else
        echo  " * MariaDB/MySQL server ${my_version} is running"
        echo  "____________________Server:_________________Client:_________________________"
        LANG=C; /usr/bin/ss -an | /usr/bin/grep ${mysql_port} |
        /usr/bin/awk '{print $1"               "$5"              "$6"               "$2}'
        echo
        echo  "____________________Internal sockets:_______________________________________"
        LANG=C; /usr/bin/ss -an | /usr/bin/grep mysql/${my_path} |
        /usr/bin/awk '{print $1"               "$2"          "$6"  "$5}'
    fi
}

# ---------------------------------------------------------------------------
# main
# ---------------------------------------------------------------------------
while [ ${#} -gt 0 ]
do
    case "${1}" in
    -q|--quiet)
        _quiet=true
        shift
        ;;
    --skip)
        skip='--skip-grant-table --skip-networking'
        shift
        ;;
    *)
        _action=${1}
        shift
        ;;
    esac
done

case "${_action}" in
    start)
        mariadb_start
    ;;
    stop)
        mariadb_stop
    ;;
    restart)
        mariadb_restart
    ;;
    status)
        mariadb_status
    ;;
    *)
        usage
        exit 1
    ;;
esac

exit 0
# ---------------------------------------------------------------------------
# end
# ---------------------------------------------------------------------------