#!/bin/sh
#
#   /etc/rc.d/init.d/tractor-engine
#
# chkconfig: 345 95 05
# description: Controls tractor-engine, the job queue manager for \
#              Pixar's Tractor distributed computing system.
# processname: tractor-engine

prog="tractor-engine"
options=/etc/sysconfig/pixar
pidfile=/var/run/$prog.pid
lockfile=/var/lock/subsys/$prog

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

# Check that networking enabled.
if [ "$NETWORKING" = "no" ]; then
    exit 0
fi

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

# Source the options file, defines engineOPTIONS
# also define engineDIR
if [ -f $options ];then
        . $options
fi

executable=$engineDIR/$prog

# Sanity check, executable exists?
test -x $executable || exit 0

RETVAL=0

#
# Set up some functions
#
start() {
    local pid
    echo -n $"Starting $prog: "
    RETVAL=0
    # Check if the daemon is already running
    pid=`pidofproc $prog`
    if [ -f $pidfile ]; then
        RETVAL=1
        if [ "$pid" == "" ]; then
            RETVAL=0
        rm -f $pidfile
        fi
    fi
    if [ $RETVAL -eq 0 ]; then
        $executable $engineOPTIONS --daemon
        RETVAL=$?
        if [ $RETVAL -eq 0 ]; then
            sleep 1
            pid=`pidofproc $prog`
            echo $pid > $pidfile
            touch $lockfile
        fi
    else
        [ "$BOOTUP" != "verbose" ] && echo_failure
    fi
    echo "$pid"
    return $RETVAL
}

reload() {
    local pid
    echo -n $"Reloading $prog: "
    RETVAL=0
    # run program without killing previous, add --supersede
    $executable $engineOPTIONS --daemon --supersede
    RETVAL=$?
    if [ $RETVAL -eq 0 ]; then
        # remove pid file so that pidofproc will look for new pid
        # default is to simply return what's listed in /var/run/*.pid
        # which contains the old engine pid
        rm -f $pidfile
        sleep 1
        pid=`pidofproc $prog`
        echo $pid > $pidfile
    fi
    echo "$pid"
    return $RETVAL
}

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



#
# Handle invocation options
#

case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
reload)
    reload
    ;;
restart)
    if [ -f $pidfile ]; then
        stop
    fi
    start
    ;;
condrestart)
    if [ -f $pidfile ]; then
        stop
        start
    fi
    ;;
status)
    status $executable
    exit $?
    ;;
*)
    echo $"Usage: $0 {start|stop|restart|condrestart|status}"
    exit 1
esac

exit $RETVAL
