#!/bin/sh -e
#
# MySQL daemon start/stop script.
#
# Debian version. Based on the original by TcX.
#

test $DEBIAN_SCRIPT_DEBUG && set -v -x 

test -x /usr/sbin/mysqld || exit 0

# Safeguard (relative paths, core dumps..)
cd /
umask 077
export PATH=/bin:/usr/bin

CONF=/etc/mysql/my.cnf
pid_file=`(test -r $CONF && grep '^pid-file' $CONF) | sed 's/.*=[\t ]*//'`
pid_file=${pid_file:-/var/run/mysqld/mysqld.pid}

case "$1" in
  'start')
	# Start daemon
	echo -n "Starting MySQL database server: mysqld"	
	/usr/bin/safe_mysqld > /dev/null 2>&1 &
	for i in 1 2 3 4 5 6; do
	  if test -f "$pid_file"; then break; fi
          sleep 1
        done
	if test -f "$pid_file"; then
          echo "."
	else
	  echo "...failed."
	fi
	;;

  'stop')
	# * As a passwordless mysqladmin (e.g. via ~/.my.cnf) must be possible
	# at least for cron, we can rely on it here, too. (although we have 
	# to specify it explicit as e.g. sudo environments points to the normal
	# users home and not /root)
	echo -n "Stopping MySQL database server: mysqld"	
	if test -f "$pid_file"; then
	  set +e
	  /usr/bin/mysqladmin --defaults-extra-file=/root/.my.cnf shutdown
	  r=$?
	  set -e
	  if [ "$r" -ne 0 ]; then
	    echo "...failed"
	    echo -e "\tYou don't seem to have the right password in /root/.my.cnf"
	    echo -n "Killing MySQL database server by signal: mysqld"
	    kill `cat $pid_file`
            for i in 1 2 3 4 5 6; do
              # mysqld should remove the pid_file when it exits.
              if ! test -f "$pid_file"; then break; fi
              sleep 1
            done
	  fi
        fi

        if test -f "$pid_file"; then
	  echo "...failed."
	else
	  echo "."
        fi
	;;

  'restart')
	set +e; $0 stop; set -e
	$0 start 
	;;

  'reload'|'force-reload')
  	echo -n "Reloading MySQL database server: mysqld"
	/usr/bin/mysqladmin reload
	echo "."
	;;

  *)
	echo "usage: $0 start|stop|restart|reload|force-reload"
	exit 1
	;;
esac

