#!/bin/sh
#
# mysql         This shell script take care of starting and stopping
#               the MySQL daemon.
#
# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB
# This file is public domain and comes with NO WARRANTY of any kind

NAME=mysqld
DAEMON=/usr/sbin/$NAME

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Should we start daemon on boot?
[ -r /etc/sysconfig/daemons/$SUBSYS ] || ONBOOT=Yes
[ ! -r /etc/sysconfig/daemons/$SUBSYS ] || . /etc/sysconfig/daemons/$SUBSYS
[ "$ONBOOT" = "no" -a "$PROBABLY" = "booting" ] && exit 0

mode=$1

basedir=/
bindir=/usr/bin
pid_file=/var/lib/mysql/mysqld.pid
mysql_daemon_user=mysql	# Run mysqld as this user.
conf=/etc/my.cnf

# The following code tries to get the variables safe_mysqld needs from the
# config file.  This isn't perfect as this ignores groups, but it should
# work as the options doesn't conflict with anything else.

if test -f "$conf"       # Extract those fields we need from config file.
then
  if grep "^datadir" $conf >/dev/null
  then
    datadir=`grep "^datadir" $conf | cut -f 2 -d= | tr -d ' '`
  fi
  if grep "^user" $conf >/dev/null
  then
    mysql_daemon_user=`grep "^user" $conf | cut -f 2 -d= | tr -d ' '`
  fi
  if grep "^pid-file" $conf >/dev/null
  then
    pid_file=`grep "^pid-file" $conf | cut -f 2 -d= | tr -d ' '`
  else
    if test -d "$datadir"
    then
      pid_file=$datadir/`hostname`.pid
    fi
  fi
  if grep "^basedir" $conf >/dev/null
  then
    basedir=`grep "^basedir" $conf | cut -f 2 -d= | tr -d ' '`
    bindir=$basedir/bin
  fi
  if grep "^bindir" $conf >/dev/null
  then
    bindir=`grep "^bindir" $conf | cut -f 2 -d=| tr -d ' '`
  fi
fi


# Safeguard (relative paths, core dumps..)
cd $basedir

case "$mode" in
  'start')
    # Start daemon
    [ ! -e $LOCK ] || exit 1
    [ -x $DAEMON ] || exit 0

    if [ -x $bindir/safe_mysqld ]
    then
#      echo -n "Starting $IDENT: "
      $bindir/safe_mysqld --user=$mysql_daemon_user --pid-file=$pid_file &
      touch $LOCK
      echo "."
    else
      echo "Can't execute $bindir/safe_mysqld"
    fi
    ;;

  'stop')
    [ -f $LOCK ] || exit 0
    # Stop daemon. We use a signal here to avoid having to know the
    # root password.
    if test -f "$pid_file"
    then
      echo -n "Stopping $IDENT: "
      mysqld_pid=`cat $pid_file`
      kill $mysqld_pid
      # mysqld should remove the pid_file when it exits.
 #     echo "."
      rm -f $LOCK
    else
      echo "No mysqld pid file found. Looked for $pid_file."
    fi
    ;;

  *)
    # usage
    echo "usage: $0 start|stop"
    exit 1
    ;;
esac
