#!/bin/sh

# erunner
#
# Copyright (c) 2002-2026 Electric Cloud, Inc.
# All rights reserved
#
# chkconfig: 35 77 20
# description: Electric Runner

### BEGIN INIT INFO
# Provides:          erunner
# Required-Start:
# Should-Start:      $time ypbind $syslog $remote_fs
# Required-Stop:     $syslog $remote_fs
# Should-Stop:       $time ypbind
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description: Electric Runner
# Description:       Start Electric Runner daemon which allows
#       execution of remtote commands on this machine.
### END INIT INFO

#
# This file is the Unix init.d startup script for the Electric Cloud erunner.
# It is meant to be installed into /etc/init.d, and linked to that location
# from /etc/rc2.d/S77erunner, so that erunner will be started automatically
# when the machine boots up.
#
# Per standard init.d script syntax, this script responds to three command-line
# options:
#
#       erunner start
#               Start the erunner process.
#
#       erunner stop
#               Terminate the erunner process, provided it was started by
#               this script (otherwise erunner does not know which PID to
#               kill).
#
#       erunner restart
#               Stop the erunner, then start the erunner.
#

# Set the process umask and PATH to known safe values.

cd /var/run
ulimit -c unlimited
umask 022

# Determine the system architecture.  This is used to find the erunner binary.

SYSTEM=`/bin/uname -s`
SYSARCH=`/bin/uname -m`

if [ "$SYSTEM" = "SunOS" ] ; then
    if [ "$SYSARCH" = "i86pc" ] ; then
        ARCH=i686_SunOS.5.10
    else
        # On Solaris Sparc we use sun4u_SunOS as the architecture for legacy 
        # reasons. With newer hardware, the machine type is actually sun4v, 
        # but at this level the distinction is unimportant.
        ARCH=sun4u_SunOS
    fi
else
    # On Linux, we always use i686 as the MACH string, even on 64-bit
    # Linux, where it technically would be x86_64.  This is for backwards
    # compatibility.

    ARCH=i686_Linux
    MACH=`/bin/uname -m`
fi

# Determine the erunner type; trim off the optional S77 or K20 that may
# be in $0.
ERUNNER_NAME=`basename $0`
ERUNNER_NAME=`echo $ERUNNER_NAME | sed -e 's/^[SK]..//'`
ECLOUD_DIR_NAME=/opt/ecloud
PORT=2411                                ;# Port on which erunner will
                                          # listen.
ERUNNER_PID_FILE=/var/run/${ERUNNER_NAME}.pid ;# Location of the file that the
                                              # erunner process ID will be
                                              # written to, and which this 
                                              # script will read it from when
                                              # trying to terminate the
                                              # erunner.

# Set the PATH
PATH=/sbin:/bin:/usr/sbin:/usr/bin:$ECLOUD_DIR_NAME/$ARCH/bin:$ECLOUD_DIR_NAME/$ARCH/bin
export PATH

# Set up shorthand references for important locations.

ECDIR=$ECLOUD_DIR_NAME                  ;# The Electric Cloud install dir.
ECBINDIR=$ECDIR/$ARCH/bin               ;# The Electric Cloud bin directory.
ERUNNER_SCRIPT=$0

export ERUNNER_PID_FILE ECLOUD_DIR_NAME ERUNNER_SCRIPT

#------------------------------------------------------------------------
# checkpid
#
#       Checks whether any of the provided pids is running.  Returns
#       0 if so, 1 if none are running.
#       
# Credits: Shamelessly copied from RH7.3's /etc/init.d/functions
#------------------------------------------------------------------------
checkpid() {
        while [ "$1" ]; do
           [ -d /proc/$1 ] && return 0
           shift
        done
        return 1
}

#------------------------------------------------------------------------
# checkStatus
#
#       Check whether erunner is running or not.
#------------------------------------------------------------------------

checkStatus() {
    if [ -r "$ERUNNER_PID_FILE" ] ; then
        ERUNNER_PID=`/bin/cat $ERUNNER_PID_FILE`
        if checkpid $ERUNNER_PID ; then
            RETVAL=0
            /bin/echo "erunner running with PID $ERUNNER_PID"
            return
        fi
    fi
    RETVAL=1
    /bin/echo "erunner is not running"
    return
}

#------------------------------------------------------------------------
# startErunner
#
#       Start erunner.
#------------------------------------------------------------------------

startErunner() {

    # Don't let non-root users start erunner
    if [ "`id | sed 's#.*uid=\([0-9]*\).*#\1#'`" != "0" ]; then
        /bin/echo "erunner may only be started by UID 0. User id was: `id`" 
        RETVAL=1
        return 
    fi

    # If erunnerd is started it writes out a pid file before checking
    # that the port is available. Hence if you start erunnerd twice
    # in succession, the second instance will overwrite the pid of
    # the first but then exit when it fails to bind to the port. 
    # In this state it is now impossible to find the original instance
    # reliably since we have lost its pid.  So we shouldn't
    # start if we detect that erunnerd is already running. 
    if [ -r "$ERUNNER_PID_FILE" ] ; then
        ERUNNER_PID=`/bin/cat $ERUNNER_PID_FILE`
        checkpid $ERUNNER_PID
        if [ $? -eq 0 ]; then
            /bin/echo "erunner is already started:  $ERUNNER_PID" 
            return
        fi
    fi

    # Rename all foo_new files in the ecloud tree to just foo.
    for i in `/usr/bin/find ${ECDIR} -type f -name "*_new"` ; do
        NEWFILE=`echo $i | sed -e 's/_new$//'`
        /bin/mv $i $NEWFILE
    done

    # Run the setupErunner script if it exists.
    if [ -f ${ECBINDIR}/setupErunner ] ; then
        ${ECBINDIR}/setupErunner
        mv ${ECBINDIR}/setupErunner ${ECBINDIR}/setupErunner.done
    fi

    # Get the erunner port from svrport.txt if it exists.
    if [ -r ${ECDIR}/${ARCH}/tmp/svrport.txt ]; then
        PORT=`/bin/cat ${ECDIR}/${ARCH}/tmp/svrport.txt`
    fi
    /bin/chmod a+x ${ECBINDIR}/erunnerd
    ${ECBINDIR}/erunnerd --port=$PORT

    if [ -d /var/lock/subsys ]; then
        /bin/touch /var/lock/subsys/$ERUNNER_NAME
    fi
}

#------------------------------------------------------------------------
# stopErunner
#
#       Attempt to terminate the erunner process by sending a SIGTERM to the
#       process whose ID is stored in the file ERUNNER_PID_FILE.  If that 
#       file does not exist, cannot be read, or contains an invalid PID,
#       the erunner will not be terminated.
#------------------------------------------------------------------------

stopErunner() {
    if [ -f /var/lock/subsys/$ERUNNER_NAME ]; then
        /bin/rm /var/lock/subsys/$ERUNNER_NAME
    fi

    if [ ! -r "$ERUNNER_PID_FILE" ] ; then
        echo "Erunner process ID (PID) file cannot be located."
        RETVAL=1
        return
    fi
    ERUNNER_PID=`/bin/cat $ERUNNER_PID_FILE`

    if checkpid $ERUNNER_PID 2>&1; then
        # Try TERM first, then KILL
        kill -TERM $ERUNNER_PID
        
        # Check that the process no longer exists.  Unfortunately,
        # Solaris doesn't have a usleep command, or else we
        # could have slept for a millisecond and done one check.  Instead
        # we just do five checks in a row (hoping that if the process
        # was going to terminate, it would do so sometime during those
        # five checks.)  If the process is still alive, sleep for a
        # second and check again.  If it's still alive, sleep for three
        # seconds and check again.  If it's still alive, kill -KILL.

        if checkpid $ERUNNER_PID && checkpid $ERUNNER_PID && checkpid $ERUNNER_PID && checkpid $ERUNNER_PID && checkpid $ERUNNER_PID && /bin/sleep 1 && checkpid $ERUNNER_PID &&  /bin/sleep 3 && checkpid $ERUNNER_PID ; then
            # Ok, the process is still alive.  Now it must feel the wrath
            # of the KILL signal!!

            kill -KILL $ERUNNER_PID

            # Ok, this really should've worked.  However, sometimes the
            # erunner is stuck because of an efs issue and really can't die.

            if checkpid $ERUNNER_PID && checkpid $ERUNNER_PID && checkpid $ERUNNER_PID && checkpid $ERUNNER_PID && checkpid $ERUNNER_PID && /bin/sleep 1 && checkpid $ERUNNER_PID ; then
                echo "Unable to kill erunner"
                RETVAL=1
            fi
        fi
    fi
}

# Parse the command line argument.
RETVAL=0
case "$1" in
    'start')
        # Start the erunner.

        startErunner
        ;;

    'stop')
        # Stop the erunner.

        stopErunner
        ;;

    'restart')
        # Stop, then start the erunner.

        stopErunner
        startErunner
        ;;

    'status')
        checkStatus
        ;;

    *)
        # Not a recognized option; just print a simple help message.

        echo "Usage: $0 { start | stop | restart }"
        ;;

esac

exit $RETVAL
