#!/bin/sh
#
# --- T2-COPYRIGHT-NOTE-BEGIN ---
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
# 
# T2 SDE: package/.../mysql/mysql.init
# Copyright (C) 2004 - 2005 The T2 SDE Project
# Copyright (C) 1998 - 2003 ROCK Linux Project
# 
# More information can be found in the files COPYING and README.
# 
# 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; version 2 of the License. A copy of the
# GNU General Public License can be found in the file COPYING.
# --- T2-COPYRIGHT-NOTE-END ---
#
# Desc: The MySQL server
# Runlevel: 30 rcX
#

title() {
	local x w="$( stty size 2>/dev/null </dev/tty | cut -d" " -f2  )"
	[ -z "$w" ] && w="$( stty size </dev/console | cut -d" " -f2  )"
	for (( x=1; x<w; x++ )) do echo -n .; done
	echo -e "\e[222G\e[3D v \r\e[36m$* \e[0m"
	error=0
}

status() {
	if [ $error -eq 0 ]
	then
		echo -e "\e[1A\e[222G\e[4D\e[32m :-)\e[0m"
	else
		echo -e "\e[1A\e[222G\e[4D\a\e[1;31m :-(\e[0m"
	fi
}

wait_for_pidfile()
{
	i=0
	while [ $i -le 30 ]; do
		case $1 in
			created) [ -s $2 ] && return 0 ;;
			removed) [ ! -s $2 ] && return 0 ;;
		esac
		i=`expr $i + 1`
		sleep 1
	done
	return 1
}

case "$1" in

   start)
	title "Starting MySQL Server."
	if ! ps -C mysqld > /dev/null 2>&1; then
		/opt/mysql/bin/mysqld_safe --pid-file=/var/opt/mysql/pid \
	                                   >/dev/null 2>&1 &
		# TODO: check if the above command was a success ...
		wait_for_pidfile created /var/opt/mysql/pid
		error=$?
	else
		echo "MySQL server already running."
		error=1
	fi

   	status
	;;

   stop)
	title "Stopping MySQL Server."
	if kill $(cat /var/opt/mysql/pid 2>/dev/null) 2>/dev/null; then
		wait_for_pidfile removed /var/opt/mysql/pid
		error=$?
	else
		error=1
		echo "No PID file for a MySQL server."
	fi
   	status
	;;

   restart)
	title "Restarting MySQL Server."
	if kill -1 $(cat /var/opt/mysql/pid 2>/dev/null) 2>/dev/null; then
		error=$?
	else
		error=1
		echo "No PID file for a MySQL server."
	fi
   	status
	;;

    *)
	echo "Usage: $0 { start | stop | restart }"
	exit 1 ;;

esac

exit 0
