#!/bin/bash
#
### BEGIN INIT INFO
# Provides:          drizzle
# Required-Start:    $network $remote_fs $syslog
# Required-Stop:     $network $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start and stop the drizzle database server daemon
# Description:       Controls the main Drizzle database server daemon "drizzled"
### END INIT INFO
#
set -e
set -u
${DEBIAN_SCRIPT_DEBUG:+ set -v -x}

# Safeguard (relative paths, core dumps..)
cd /
umask 077

if [ -r "/lib/lsb/init-functions" ]; then
  . /lib/lsb/init-functions
else
  echo "E: /lib/lsb/init-functions not found, lsb-base (>= 3.0-6) needed"
  exit 1
fi

if init_is_upstart; then
    case "$1" in
	stop)
	    exit 0
	    ;;
	*)
	    exit 1
	    ;;
    esac
fi	

SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
CONF=/etc/drizzle/drizzled.cnf
DRIZZLE=/usr/bin/drizzle
DAEMON=/usr/sbin/drizzled
DRIZZLE_USER=drizzle
LOG_DIR=/var/log/drizzle
LOG=${LOG_DIR}/drizzled.log

test -x ${DAEMON} || exit 0

[ -f /etc/default/drizzled ] && . /etc/default/drizzled

# priority can be overriden and "-s" adds output to stderr
ERR_LOGGER="logger -p daemon.err -t /etc/init.d/drizzle -i"


# Check for the existance of the js plugin
JS_OPTS=""
[[ -f usr/lib/drizzle/libjs_plugin.so ]] || JS_OPTS="--plugin-remove=js"


## Fetch a particular option from drizzle's invocation.
#
# Usage: void drizzled_get_param option
drizzled_get_param() {
	$DAEMON $JS_OPTS --help --user=${DRIZZLE_USER} \
    | grep "^$1" \
    | awk '{print $2}'
}
# datadir and pidfile are broken at the moment, use the debian defaults here:
#PIDFILE=`drizzled_get_param pid-file`
#DATADIR=`drizzled_get_param datadir`
#[ -z $DATADIR ] && DATADIR=/var/lib/drizzle
#[ -z $PIDFILE ] && PIDFILE=$DATADIR/`hostname -s`.pid
DATADIR=/var/lib/drizzle
PIDFILE=$DATADIR/`hostname -s`.pid


## Checks if there is a server running and if so if it is accessible.
#
# check_alive insists on a pingable server
# check_dead also fails if there is a lost drizzled in the process list
#
# Usage: boolean drizzled_status [check_alive|check_dead] [warn|nowarn]
drizzled_status () {
    ping_output=`$DRIZZLE $JS_OPTS --ping 2>&1`; ping_alive=$(( ! $? ))

    ps_alive=0
    if [ -f "$PIDFILE" ] && ps `cat $PIDFILE` >/dev/null 2>&1; then ps_alive=1; fi

    if [ "$1" = "check_alive"  -a  $ping_alive = 1 ] ||
       [ "$1" = "check_dead"   -a  $ping_alive = 0  -a  $ps_alive = 0 ]; then
	return 0 # EXIT_SUCCESS
    else
  	if [ "$2" = "warn" ]; then
  	    echo -e "$ps_alive processes alive and '$DRIZZLE --ping' resulted in\n$ping_output\n" | $ERR_LOGGER -p daemon.debug
	fi
  	return 1 # EXIT_FAILURE
    fi
}

# Checks to see if something is already running on the port we want to use
check_protocol_port() {
    local service=$1

    port=`drizzled_get_param $1`

    if [ "x$port" != "x" ] ; then
        count=`netstat --listen --numeric-ports | grep \:$port | grep -c . `

        if [ $count -ne 0 ]; then
            log_failure_msg "The selected $service port ($port) seems to be in use by another program "
            log_failure_msg "Please select another port to use for $service"
            return 1
        fi
    fi
    return 0
}

#
# main()
#

case "${1:-''}" in
  'start')
    [ -e "${DATADIR}" ] || \
      install -d -o${DRIZZLE_USER} -g${DRIZZLE_USER} -m750 "${DATADIR}"
    [ -d /var/run/drizzle ] || install -d -o $DRIZZLE_USER -g $DRIZZLE_USER /var/run/drizzle
    # Start daemon
    log_daemon_msg "Starting Drizzle database server" "drizzled"
    check_protocol_port mysql-protocol-port || log_end_msg 0
    check_protocol_port drizzle-protocol-port || log_end_msg 0
    if [ -f "$PIDFILE" ] && ps `cat $PIDFILE` >/dev/null 2>&1;
    then
        log_progress_msg "(already running)"
        log_end_msg 0
    else
        start_daemon "$DAEMON --chuid $DRIZZLE_USER -m" "--datadir=$DATADIR" "--pid-file=$PIDFILE" "$JS_OPTS" >> $LOG 2>&1 &
        log_progress_msg "drizzled"
        log_end_msg 0
    fi
  ;;

  'stop')
    log_daemon_msg "Stopping Drizzle database server" "drizzled"
    if [ -f "$PIDFILE" ]; then
        killproc -p "$PIDFILE" "$DAEMON"
        log_progress_msg "drizzled"
    fi
    log_end_msg 0
  ;;

  'restart'|'force-reload')
    set +e; $SELF stop; set -e
    $SELF start
    ;;

  'status')
    if drizzled_status check_alive nowarn; then
      log_action_msg "Drizzle is alive."
    else
      log_action_msg "Drizzle is stopped."
      exit 3
    fi
    ;;

  *)
    echo "Usage: $SELF start|stop|restart|status"
    exit 1
  ;;

esac

