#!/bin/bash
# Licensed under the OpenIB.org BSD license (FreeBSD Variant) - See COPYING.md
#
# Bring up/down the ibacm daemon
#
# chkconfig: 2345 25 75
# description: Starts/Stops InfiniBand ACM service
#
### BEGIN INIT INFO
# Provides:       ibacm
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Required-Start: $network $remote_fs
# Required-Stop: $network $remote_fs
# Should-Start:
# Should-Stop:
# Short-Description: Starts and stops the InfiniBand ACM service
# Description: The InfiniBand ACM service provides a user space implementation
#	of something resembling an ARP cache for InfiniBand SA queries and
#	host route lookups.
### END INIT INFO

pidfile=@CMAKE_INSTALL_FULL_RUNDIR@/ibacm.pid
subsys=/var/lock/subsys/ibacm

daemon() { /sbin/daemon   ${1+"$@"}; }

if [ -s /etc/init.d/functions ]; then
	# RHEL / CentOS / SL / Fedora
	. /etc/init.d/functions
        _daemon()   { daemon ${1+"$@"}; }
        _checkpid() { checkpid `cat $pidfile`; }
        _success()  { success; echo; }
        _failure()  { failure; echo; }
elif [ -s /lib/lsb/init-functions ]; then
	# SLES / OpenSuSE / Debian
	. /lib/lsb/init-functions
	_daemon()   { start_daemon "$@"; }
        _checkpid() { checkproc -p $pidfile @CMAKE_INSTALL_FULL_SBINDIR@/ibacm; }
	_success()  { log_success_msg; }
	_failure()  { log_failure_msg; }
elif [ -s /etc/rc.status ]; then
	# Older SuSE
	. /etc/rc.status
	_daemon()   { /sbin/start_daemon ${1+"$@"}; }
        _checkpid() { checkproc -p $pidfile @CMAKE_INSTALL_FULL_SBINDIR@/ibacm; }
	_success()  { rc_status -v; }
	_failure()  { rc_status -v; }
fi	

start()
{
    echo -n "Starting ibacm daemon:"
    _daemon @CMAKE_INSTALL_FULL_SBINDIR@/ibacm
    if [[ $RETVAL -eq 0 ]]; then
        _success
    else
        _failure
    fi
}

stop()
{
    echo -n "Stopping ibacm daemon:"
    killproc -p $pidfile ibacm
    if [[ $RETVAL -eq 0 ]]; then
        _success
    else
        _failure
    fi
    rm -f $subsys
}

status()
{
    echo -n "Checking for ibacm service "
    if [ ! -f $subsys -a ! -f $pidfile ]; then
        RETVAL=3
    elif [ -f $pidfile ]; then
        _checkpid
        RETVAL=$?
    elif [ -f $subsys ]; then
        RETVAL=2
    else
        RETVAL=0
    fi
    if [[ $RETVAL -eq 0 ]]; then
        _success
    else
        _failure
    fi
}

restart ()
{
    stop
    start
}

condrestart ()
{
    [ -e $subsys ] && restart || return 0
}

usage ()
{
    echo
    echo "Usage: `basename $0` {start|stop|restart|condrestart|try-restart|force-reload|status}"
    echo
    return 2
}

case $1 in
    start|stop|restart|condrestart|try-restart|force-reload)
	[ `id -u` != "0" ] && exit 4 ;;
esac

case $1 in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart | reload)
        restart
        ;;
    condrestart | try-restart | force-reload)
        condrestart
        ;;
    status)
        status
        ;;
    *)
        usage
        ;;
esac

exit $RETVAL
