#!/bin/bash
#
# ndb_mgmd	This shell script takes care of starting and stopping
#		the MySQL Cluster management daemon (ndb_mgmd).
#
# chkconfig: - 62 38
# description:	MySQL Cluster management daemon.
# processname: ndb_mgmd
# config: /var/lib/mysql-cluster/config.ini
# pidfile: /var/lib/mysql-cluster/ndb_${node_id}.pid

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

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


prog="ndb_mgmd"

# extract value of a MySQL option from config files
# Usage: get_mysql_option SECTION VARNAME DEFAULT
# result is returned in $result
# We use my_print_defaults which prints all options from multiple files,
# with the more specific ones later; hence take the last match.
get_mysql_option(){
	result=`/usr/bin/my_print_defaults --extra-file=/var/lib/mysql-cluster/config.ini "$1" | sed -n "s/^--$2=//p" | tail -n 1`
	if [ -z "$result" ]; then
	    # not found, use default
	    result="$3"
	fi
}

get_mysql_option ndb_mgmd id "1"
node_id="$result"
errlogfile="/var/lib/mysql-cluster/ndb_${node_id}_out.log"
pidfile="/var/lib/mysql-cluster/ndb_${node_id}.pid"

# For SELinux we need to use 'runuser' not 'su'
if [ -x /sbin/runuser ]
then
    SU=runuser
else
    SU=su
fi

start(){
	touch "$errlogfile"
	chown mysql:mysql "$errlogfile" 
	chmod 0640 "$errlogfile"
	[ -x /sbin/restorecon ] && /sbin/restorecon "$errlogfile"

	# all options are expected to be specified in
	# /var/lib/mysql-cluster/config.ini.
	$SU -l mysql -c "cd /var/lib/mysql-cluster; /usr/libexec/ndb_mgmd" >> "$errlogfile" 2>&1 < /dev/null
	ret=$?
	if [ $ret -eq 0 ]; then
	    action $"Starting $prog: " /bin/true
	else
    	    action $"Starting $prog: " /bin/false
	fi
	[ $ret -eq 0 ] && touch /var/lock/subsys/ndb_mgmd
	return $ret
}

stop(){
        NDB_MGMD_PID=`cat "$pidfile"  2>/dev/null `
        if [ -n "$NDB_MGMD_PID" ]; then
	    /usr/bin/ndb_mgm -e shutdown >/dev/null
            ret=$?
            if [ $ret -eq 0 ]; then
		rm -f /var/lock/subsys/ndb_mgmd
		rm -f "$pidfile"
		action $"Stopping $prog: " /bin/true
            else
                action $"Stopping $prog: " /bin/false
            fi
        else
            ret=1
            action $"Stopping $prog: " /bin/false
        fi
        return $ret
}
 
restart(){
    stop
    start
}

condrestart(){
    [ -e /var/lock/subsys/ndb_mgmd ] && restart || :
}

# See how we were called.
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
    status ndb_mgmd
    ;;
  restart)
    restart
    ;;
  condrestart)
    condrestart
    ;;
  *)
    echo $"Usage: $0 {start|stop|status|condrestart|restart}"
    exit 1
esac

exit $?