#!/bin/sh 
#
# based on the ''Example init.d script with LSB support.''
#
# Copyright (c) 2007 Javier Fernandez-Sanguino <jfs@debian.org>
#
# This is free software; you may redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2,
# or (at your option) any later version.
#
# This is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License with
# the Debian operating system, in /usr/share/common-licenses/GPL;  if
# not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA 02111-1307 USA
#
### BEGIN INIT INFO
# Provides:          ctdb
# Required-Start:    $network $local_fs $remote_fs
# Required-Stop:     $network $local_fs $remote_fs
# Should-Start:      
# Should-Stop:       
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: start ctdb daemon
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

DAEMON=/usr/sbin/ctdbd # Introduce the server's location here
NAME=ctdb              # Introduce the short server's name here
DESC="Clustered TDB"              # Introduce a short description here


test -x $DAEMON || exit 0
test -x $DAEMON_WRAPPER || exit 0

. /lib/lsb/init-functions

[ -z "$CTDB_BASE" ] && {
    export CTDB_BASE="/etc/ctdb"
}

. $CTDB_BASE/functions

# Default options, these can be overriden by the information
# at /etc/default/$NAME
CTDB_OPTIONS=""          # Additional options given to the server 

LOGFILE=$LOGDIR/$NAME.log  # Server logfile
#DAEMONUSER=ctdb   # Users to run the daemons as. If this value
                        # is set start-stop-daemon will chuid the server

# Include defaults if available
if [ -f /etc/default/$NAME ] ; then
	. /etc/default/$NAME
fi

[ -z "$CTDB_RECOVERY_LOCK" ] && {
    echo "You must configure the location of the CTDB_RECOVERY_LOCK"
    exit 1
}
CTDB_OPTIONS="$CTDB_OPTIONS --reclock=$CTDB_RECOVERY_LOCK"

# build up CTDB_OPTIONS variable from optional parameters
[ -z "$CTDB_LOGFILE" ]          || CTDB_OPTIONS="$CTDB_OPTIONS --logfile=$CTDB_LOGFILE"
[ -z "$CTDB_NODES" ]            || CTDB_OPTIONS="$CTDB_OPTIONS --nlist=$CTDB_NODES"
[ -z "$CTDB_SOCKET" ]           || CTDB_OPTIONS="$CTDB_OPTIONS --socket=$CTDB_SOCKET"
[ -z "$CTDB_PUBLIC_ADDRESSES" ] || CTDB_OPTIONS="$CTDB_OPTIONS --public-addresses=$CTDB_PUBLIC_ADDRESSES"
[ -z "$CTDB_PUBLIC_INTERFACE" ] || CTDB_OPTIONS="$CTDB_OPTIONS --public-interface=$CTDB_PUBLIC_INTERFACE"
[ -z "$CTDB_SINGLE_PUBLIC_IP" ] || CTDB_OPTIONS="$CTDB_OPTIONS --single-public-ip=$CTDB_SINGLE_PUBLIC_IP"
[ -z "$CTDB_DBDIR" ]            || CTDB_OPTIONS="$CTDB_OPTIONS --dbdir=$CTDB_DBDIR"
[ -z "$CTDB_DBDIR_PERSISTENT" ] || CTDB_OPTIONS="$CTDB_OPTIONS --dbdir-persistent=$CTDB_DBDIR_PERSISTENT"
[ -z "$CTDB_EVENT_SCRIPT_DIR" ] || CTDB_OPTIONS="$CTDB_OPTIONS --event-script-dir $CTDB_EVENT_SCRIPT_DIR"
[ -z "$CTDB_TRANSPORT" ]        || CTDB_OPTIONS="$CTDB_OPTIONS --transport $CTDB_TRANSPORT"
[ -z "$CTDB_DEBUGLEVEL" ]       || CTDB_OPTIONS="$CTDB_OPTIONS -d $CTDB_DEBUGLEVEL"
[ -z "$CTDB_START_AS_DISABLED" ] || [ "$CTDB_START_AS_DISABLED" != "yes" ] || {
        CTDB_OPTIONS="$CTDB_OPTIONS --start-as-disabled"
}
[ -z "$CTDB_CAPABILITY_RECMASTER" ] || [ "$CTDB_CAPABILITY_RECMASTER" != "no" ] || {
	CTDB_OPTIONS="$CTDB_OPTIONS --no-recmaster"
}
[ -z "$CTDB_CAPABILITY_LMASTER" ] || [ "$CTDB_CAPABILITY_LMASTER" != "no" ] || {
	CTDB_OPTIONS="$CTDB_OPTIONS --no-lmaster"
}
[ -z "$CTDB_LVS_PUBLIC_IP" ] || {
       CTDB_OPTIONS="$CTDB_OPTIONS --lvs"
}

# Check that the user exists (if we set a user)
# Does the user exist?
if [ -n "$DAEMONUSER" ] ; then
    if getent passwd | grep -q "^$DAEMONUSER:"; then
        # Obtain the uid and gid
        DAEMONUID=`getent passwd |grep "^$DAEMONUSER:" | awk -F : '{print $3}'`
        DAEMONGID=`getent passwd |grep "^$DAEMONUSER:" | awk -F : '{print $4}'`
    else
        log_failure_msg "The user $DAEMONUSER, required to run $NAME does not exist."
        exit 1
    fi
fi


set -e

running() {
    ps -e | awk  '{print $4}' | grep "^ctdbd$" > /dev/null && return 0
    return 1
}

start_server() {
        # check all persistent databases that they look ok
        PERSISTENT_DB_DIR="/var/lib/ctdb/persistent"
        [ -z "$CTDB_DBDIR" ] || {
                PERSISTENT_DB_DIR="$CTDB_DBDIR/persistent"
        }
        mkdir -p $PERSISTENT_DB_DIR 2>/dev/null
	for PDBASE in `ls $PERSISTENT_DB_DIR/*.tdb.[0-9] 2>/dev/null`; do
                /usr/bin/tdbdump $PDBASE >/dev/null 2>/dev/null || {
                        echo "Persistent database $PDBASE is corrupted! CTDB will not start."
                        return 1
                }
        done
        # Start the process using the wrapper
        if [ "$CTDB_VALGRIND" = "yes" ]; then
	    valgrind -q --log-file=/var/log/ctdb_valgrind \
		$DAEMON --nosetsched $CTDB_OPTIONS 
	else if [ -z "$DAEMONUSER" ] ; then
            start-stop-daemon --start --quiet --background \
                        --exec $DAEMON -- $CTDB_OPTIONS
            errcode=$?
        else
# if we are using a daemonuser then change the user id
            start-stop-daemon --start --quiet --background \
                        --chuid $DAEMONUSER \
                        --exec $DAEMON -- $CTDB_OPTIONS
            errcode=$?
        fi
	fi
	sleep 1
	# set any tunables from the config file
	set | grep ^CTDB_SET_ | cut -d_ -f3- | 
	while read v; do
	    varname=`echo $v | cut -d= -f1`
	    value=`echo $v | cut -d= -f2`
	    ctdb setvar $varname $value || errcode=1
	done || exit 1
	return $errcode
}

stop_server() {
# Stop the process using the wrapper
        ctdb shutdown
	errcode=$?
        if [ "$CTDB_VALGRIND" = "yes" ]; then
	    # very crude method
	    sleep 2
	    pkill -9 -f valgrind
	else if [ -z "$DAEMONUSER" ] ; then
            start-stop-daemon --stop --quiet \
                        --exec $DAEMON
            errcode=$?
        else
# if we are using a daemonuser then look for process that match
            start-stop-daemon --stop --quiet \
                        --user $DAEMONUSER \
                        --exec $DAEMON
            errcode=$?
        fi
	fi
	count=0
	while killall -q -0 ctdbd; do
	    sleep 1
	    count=`expr $count + 1`
	    [ $count -gt 10 ] && {
		echo -n "killing ctdbd "
		killall -q -9 ctdbd
		pkill -9 -f $CTDB_BASE/events.d/
	    }
	done

	return $errcode
}

case "$1" in
  start)
	log_daemon_msg "Starting $DESC " "$NAME"
        # Check if it's running first
        if running ;  then
            log_progress_msg "already running"
            log_end_msg 0
            exit 0
        fi
        if start_server && running ;  then
            # It's ok, the server started and is running
            log_end_msg 0
        else
            # Either we could not start it or it is not running
            # after we did
            # NOTE: Some servers might die some time after they start,
            # this code does not try to detect this and might give
            # a false positive (use 'status' for that)
            log_end_msg 1
        fi
	;;
  stop)
        log_daemon_msg "Stopping $DESC" "$NAME"
        if running ; then
            # Only stop the server if we see it running
            stop_server
            log_end_msg $?
        else
            # If it's not running don't do anything
            log_progress_msg "not running"
            log_end_msg 0
            exit 0
        fi
        ;;
  restart|force-reload)
        log_daemon_msg "Restarting $DESC" "$NAME"
        running && stop_server
        start_server
        running
        log_end_msg $?
	;;
  status)

        log_daemon_msg "Checking status of $DESC" "$NAME"
        if running ;  then
            log_progress_msg "running"
	    echo
	    ctdb status
            log_end_msg 0
        else
            log_progress_msg "not running"
            log_end_msg 0
            exit 3
        fi
        ;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
