#!/bin/bash
#
# ovirt-ha-agent        Start the oVirt Hosted Engine HA Monitoring Agent
#
# chkconfig: 2345 97 3
# description: ovirt-ha-agent - communications agent for the oVirt \
#              Hosted Engine High Availability project.
#
# processname: ovirt-ha-agent

### BEGIN INIT INFO
# Provides: ovirt-ha-agent
# Required-Start: $local_fs $syslog ovirt-ha-broker
# Required-Stop: $local_fs $syslog ovirt-ha-broker
# Should-Start: $syslog
# Should-Stop: $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start the oVirt Hosted Engine High Availability Monitoring Agent
# Description: ovirt-ha-agent - monitoring agent for the oVirt
#              Hosted Engine High Availability project.
### END INIT INFO

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

RETVAL=0
prog="ovirt-ha-agent"
lockfile=/var/lock/subsys/$prog

AGENT=/usr/share/ovirt-hosted-engine-ha/ovirt-ha-agent
ENGINE_SETUP_CONF_FILE=/etc/ovirt-hosted-engine/hosted-engine.conf

[ -f /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog

runlevel=$(set -- $(runlevel); eval "echo \$$#" )

start()
{
    [ -x $AGENT ] || exit 5
    if [ ! -f $ENGINE_SETUP_CONF_FILE ]; then
        if [ -f /etc/default/ovirt ]; then
            # See https://bugzilla.redhat.com/1164226
            echo -n "Not starting $prog on Node before deployment"
            exit 0
        else
            echo "Configuration by ovirt-hosted-engine-setup is required"
            echo "File: $ENGINE_SETUP_CONF_FILE"
            exit 6
        fi
    fi
    echo -n $"Starting $prog: "
    $AGENT $OPTIONS && success || failure
    RETVAL=$?
    [ $RETVAL -eq 0 ] && touch $lockfile
    echo
    return $RETVAL
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $AGENT
    RETVAL=$?
    [ $RETVAL -eq 0 ] && rm -f $lockfile
    echo
}

restart() {
    stop
    start
}

reload() {
    restart
}

force_reload() {
    restart
}

rh_status() {
    status $prog
    RETVAL=$?
    return $RETVAL
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        start
        ;;
    stop)
        if ! rh_status_q; then
            rm -f $lockfile
            exit 0
        fi
        stop
        ;;
    status)
        rh_status
        ;;
    restart)
        restart
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
        restart
        ;;
    reload)
        rh_status_q || exit 7
        reload
        ;;
    force-reload)
        force_reload
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        RETVAL=2
esac
exit $RETVAL
