#!/bin/sh
# ganeti node daemon starter script
# based on skeleton from Debian GNU/Linux
### BEGIN INIT INFO
# Provides:          ganeti
# Required-Start:    $syslog $remote_fs
# Required-Stop:     $syslog $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Ganeti Cluster Manager
# Description:       Ganeti Cluster Manager
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
DESC="Ganeti cluster"

DAEMON_UTIL=/usr/lib/ganeti/daemon-util

SCRIPTNAME="/etc/init.d/ganeti"

test -f "$DAEMON_UTIL" || exit 0

. /etc/init.d/functions

check_exitcode() {
    RC=$1

    if errmsg=$($DAEMON_UTIL check-exitcode $RC)
    then
        success "$errmsg"
    else
        failure "$errmsg"
    fi
}

start_action() {
    # called as start_action daemon-name
    local daemon="$1"
    $DAEMON_UTIL start "$@"
    check_exitcode $?
}

stop_action() {
    # called as stop_action daemon-name
    local daemon="$1"
    $DAEMON_UTIL stop "$@"
    check_exitcode $?
}

check_gnt_service() {
 $DAEMON_UTIL check "$1"
 if [ $? -eq 0 ]; then
  echo "$1 is running" && success
 else
  echo "$1 is not running" && failure
 fi
}

status_action() {
 if [ ! -z "$1" ]; then
    check_gnt_service "$1"
 else
    check_gnt_service ganeti-noded
    check_gnt_service ganeti-confd
    check_gnt_service ganeti-masterd
    check_gnt_service ganeti-rapi
 fi
}

condrestart_action() {
    $DAEMON_UTIL check ganeti-noded || $DAEMON_UTIL check ganeti-confd || $DAEMON_UTIL check ganeti-masterd || $DAEMON_UTIL check ganeti-rapi
    if [ $? = 0 ]; then
	echo "Restarting $DESC"
	stop_all
	start_all
    fi
}

maybe_do() {
    requested="$1"; shift
    action="$1"; shift
    target="$1"
    if [ -z "$requested" -o "$requested" = "$target" ]; then
        $action "$@"
    fi
}

start_all() {
    if ! $DAEMON_UTIL check-config; then
        failure "Incomplete configuration, will not run."
        exit 0
    fi

    for i in $($DAEMON_UTIL list-start-daemons); do
        maybe_do "$1" start_action $i
    done
}

stop_all() {
    for i in $($DAEMON_UTIL list-stop-daemons); do
        maybe_do "$1" stop_action $i
    done
}

if [ -n "$2" ] && ! errmsg=$($DAEMON_UTIL is-daemon-name "$2" 2>&1); then
    failure "$errmsg"
    exit 1
fi

case "$1" in
    start)
        msg_starting "$DESC $2"
        start_all "$2"
        ;;
    stop|condstop)
        msg_stopping "$DESC $2"
        stop_all "$2"
        ;;
    status)
	status_action "$2"
	;;
    condrestart)
	condrestart_action "$2"
	;;
    restart|force-reload)
        echo "Restarting $DESC $2"
        stop_all "$2"
        start_all "$2"
        ;;
    *)
        msg_usage "Usage: $SCRIPTNAME {start|stop|force-reload|restart|status|condstop|condrestart}"
        exit 1
        ;;
esac

exit 0
