#!/bin/sh
# chkconfig: 2345 51 49
### BEGIN INIT INFO
# Provides:          MariaDB
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Should-Start:      $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start Mariadb at boot time
# Description:       Enable service provided by Mariadb.
# X-Start-Before:    
# X-Stop-After:      
# X-Timesys-Start-Number:  51
# X-Timesys-Stop-Number:  49
### END INIT INFO


PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/scripts

DATADIR=/var/mysql
PID=


initial_setup() {

  if [ -z "$(grep ^mysql /etc/passwd 2>/dev/null)" ]; then
    echo "$0: Creating system user 'mysql' with generic settings.  Review and modify as required."
    yes '' | adduser mysql >/dev/null 2>&1 || yes '' | useradd mysql >/dev/null 2>&1
  fi

  if [ ! -d $DATADIR ]; then
    mysql_install_db --user=mysql --datadir=$DATADIR --basedir=/usr
  fi

  chown -R mysql $DATADIR

}

read_pid() {
  PIDFILE=${DATADIR}/*.pid
  if [ -f $PIDFILE ]; then
    PID=`cat ${PIDFILE}`
    if [ ! ${PID:=0} -gt 1 -a "X$PID" = "X " ]; then
      echo "Unable to read process ID from pid file"
    fi
  else
    echo "No pid file found."
  fi

  if [ -z "$PID" ]; then
    exit 1
  fi
}

stop_service() {
  read_pid
  
  if [ -n "$PID" ]; then
    echo "Stopping mysqld"
    kill ${PID}
    pidof mysqld > /dev/null
    while [ $? -eq 0 ]; do
      sleep 1
      pidof mysqld > /dev/null
    done
  fi
}

start_service() {
  mysqld_safe --user=$USER --datadir=$DATADIR &
}

reload_service() {
  read_pid
  
  if [ -n "$PID" ]; then
    kill -HUP $PID
  fi
}

status_of_service() {
  read_pid
  
  if [ -n "$PID" ]; then
    if kill -0 $PID 2>/dev/null ; then
      echo "MariaDB is running"
    else
      echo "MariaDB is NOT running"
    fi
  fi
}

case "$1" in
  start)
    initial_setup
    start_service
  ;;
  stop)
    stop_service
  ;;
  restart)
    $0 stop
    $0 start
  ;;
  status)
    status_of_service
  ;;
  reload)
    reload_service
  ;;
  *)
    echo "$0 [start|stop|restart|reload|status]"
  ;;
esac
