#!/bin/sh
#
# xcatd:         serial-port console daemon
#
# chkconfig:     2345 85 60
# description:   xCAT management service
# processname:   xcatd
# config:        /etc/sysconfig/xcat

WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/init.d/functions

# Source networking configuration.
SourceIfNotEmpty /etc/sysconfig/network

# This avoids the perl locale warnings
if [ -z $LC_ALL ]; then
  export LC_ALL=C
fi

# xCAT settings.
if [ -r /etc/sysconfig/xcat ]; then
    . /etc/sysconfig/xcat
fi

if [ -r /etc/profile.d/xcat.sh ]; then
    . /etc/profile.d/xcat.sh
fi

RETVAL=0
PIDFILE=/var/run/xcatd.pid
LOCKFILE=/var/lock/subsys/xcatd

start() {
    is_yes "$NETWORKING" || return 0
    start_daemon --displayname xCAT --name perl --lockfile "$LOCKFILE" --pidfile "$PIDFILE" --expect-user root -- xcatd -p "$PIDFILE"
    RETVAL=$?

    return $RETVAL
}

stop() {
    # We need kill all process group
   
    # TEST
    start-stop-daemon --test --stop --name perl --pidfile "$PIDFILE" --user root > /dev/null
    RETVAL=$?

    if [ $RETVAL -ne 0 ] ; then
            msg_not_running "xCAT"
            [ -z "$LOCKFILE" ] || rm -f "$LOCKFILE"
            passed "xCAT"
            STATUS=$?
            echo
            return $STATUS
    fi

    # KILL
    gp="$(cat "$PIDFILE")"
    stop_daemon --displayname 'xCAT' --name perl --lockfile "$LOCKFILE" --pidfile "$PIDFILE" --expect-user root -- xcatd
    RETVAL=$?
   
    if [ $RETVAL -eq 0 ] &&  pgrep -g $gp > /dev/null; then
            kill -TERM -$gp
    fi
    
    return $RETVAL
}

restart() {
    stop
    start
}

case "$1" in
    start)
    start
    ;;
    stop)
    stop
    ;;
    restart)
    restart
    ;;
    reload)
    restart
    ;;
    status)
    status --name 'perl' --displayname 'xCAT' --pidfile "$PIDFILE" --expect-user root -- xcatd
    RETVAL=$?
    ;;
    condstart)
    if ! [ -f "$LOCKFILE" ]; then
    start
    fi
    ;;
    condstop)
    if [ -f "$LOCKFILE" ]; then
    stop
    fi
    ;;
    condrestart)
    if [ -f "$LOCKFILE" ]; then
    restart
    fi
    ;;
    condreload)
    if [ -f "$LOCKFILE" ]; then
    restart
    fi
    ;;
    *)
    msg_usage "${0##*/} {start|stop|status|restart|reload|condstart|condstop|condrestart|condreload}"
    RETVAL=1
    ;;
esac

exit $RETVAL
