#! /bin/sh
#
# Last updated 27 April 2005.
#
# start.cdtool is a script that can be used to start a CD Tool, and to
# automatically restart the CD Tool if it happens to stop. start.cdtool
# can currently be used to start CD Receiver, CD Sender or CD2W. start.cdtool
# takes three mandatory command-line arguments and four optional command-line 
# arguments:
#
# Mandatory arguments
# -p PROGRAM - full path to the CD Tool to start. 
# -c CONFIG_FILE - configuration file to be read by the CD Tool.
# -l LOG_DIR - directory that contains the log file written by the CD Tool.
#
# Optional arguments
# -o OPER - when the CD Tool is started or is stopped, mail is sent to the
#        user specified by oper. If the list is in quotes and comma separated 
#        then mail is sent to all of the users in the list. 
# -h HOSTNAME - the name of the host where the script should be run. If this 
#        name does not match the output of the 'hostname' command, the script 
#        will exit with a fatal error. If this argument is not given, this 
#        check is skipped. 
# -u USERNAME - the name of the user which should run this script. If this name
#        does not match the output of the 'whoami' command, the script will 
#        exit with a fatal error. If this argument is not given, this check 
#        is skipped. 
# -s LOGSTRING - a string which is added to the name of the logfile, to help 
#        with identification. If used, the log file will be named:
#            $program_name.$port.$PID.$LOGSTRING.log
#        If LOGSTRING is not given, the log file will be named:
#             $program_name.$port.$PID.log
#
#
# After start.cdtool is started, it verifies that the proper parameters were
# passed on the command line, and adjusts the environment. By default, the 
# adjustment is done by sourcing the file /etc/profile,
# since the file may be needed to set the environment variable LD_LIBRARY_PATH
# correctly. The umask is then set to 022, which will create log files with the 
# permission of -rw-r--r--
#
# A check is then made to see if the script is already running for the same cd 
# tool and config file. If there is another instance, the start script exits 
# with a fatal error.
#
# start.cdtool then checks that the program is running on the proper host by 
# the correct user. The check is done only if the -h HOSTNAME and/or 
# -u USERNAME aguments are given on the command line.
#
# start.cdtool then checks that the $program can be executed,
# $logdir can be written to, and $config_file can be read.
# The log filename is generated. If $LOGSTRING is specified with the -s argument
# the log file will have the form $program_name.$port.$PID.$LOGSTRING.log
# Otherwise the log file will have the form $program_name.$port.$PID.log
# The log file with that name is removed if it exists.
# start.cdtool then enters a loop, where it reports the day and time (UTC)
# and logs a startup message to syslog and sends a message to $OPER.
# The program is then started with the specified configuration file, and
# stdout and stderr of the CD Tool are redirected to the log file.
# If the CD Tool stops, start.cdtool reports the termination time and
# logs this to syslog and sends a message to $OPER.
#
# If the CD Tool has stopped within 60 seconds of starting, it may indicate a 
# severe problem, such as a bad configuration parameter, or a full disk. 
# In such cases of a short run time, the event is logged to syslog 
# and a message is sent to $OPER. The script will then sleep for a while, and 
# will try to restart the cd tool. The first time this happens the script 
# sleeps for 60 seconds. If it fails again within 60 seconds, it will then wait 
# 120 seconds, and then double the sleep time for each successive failure that 
# occurs within 60 seconds of each start time. This sleep time increases until 
# MAX_WAIT_TIME seconds (value 1920 seconds, i.e., 32 minutes). Each successive
# 60 second restart after that point will be every 1920 seconds, forever, until
# the underlying problem is resolved.
#
# The script exports a logical called 'DEBUG_LEVEL' and initialises it to zero. 
# This logical can be used in the CD Tool's configuration file to set the 
# debug level (e.g. 'debugLevel=$(DEBUG_LEVEL)'). If the CD Tool has stopped 
# within 60 seconds of starting, the script sets the 'DEBUG_LEVEL' level to 5. 
# This means that the next time the CD Tool starts it will generate detailed 
# debug information to allow the problem to be traced. The script resets 
# 'DEBUG_LEVEL' to zero for subsequent restarts. 'DEBUG_LEVEL' will only be 
# set to 5 again if the CD Tool runs for more than 60 seconds, restarts and 
# then stops within 60 seconds. This prevents the log file becoming too large.
#
# If the CD Tool stops more than 60 seconds after it started, start.cdtool will 
# reset the sleep time to 60 seconds, sleep for this time (to allow a new 
# version of the CD Tool to be installed), and then restart the CD Tool.
#
# NOTE: This loop of restarting the CD Tool will never exit, unless:
# a) start.cdtool is sent a kill signal
# b) armageddon arrives
#
# ##############################################################################
#
# start.cdtool requires the following programs to be in the $PATH:
# date, echo, logger, mailx, sed, sleep, hostname, whoami
#
# most commands are just assumed to be in the $PATH. the exceptions are date 
# and mailx
#
# path to a version of the date command which accepts the %s option.
# The Solaris version of date DOES NOT ACCEPT the %s option!
#
# path to the mail program, which can handle expressions like:
# $MAIL_APP -s "$msg" $OPER < /dev/null
#
# path to the ps program, which can handle expressions like
# `ps axww` 
#
# in some cases there may be a shared library which needs to be added
# using LD_LIBRARY_PATH
#
# If LD_LIBRARY_PATH is required by cdrecv and is not set properly,
# cdrecv will fail to start, and will report the following type message:
# ld.so.1: /your/path/cdrecv: fatal: liblber.so.2: open failed: No such
# file or directory
# If you get such messages, add the next two lines to the desired 
# OS block and correct the path
#
# LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/OSS/lib
# export LD_LIBRARY_PATH
#
SYS=`uname -s -r`
case $SYS in
  'SunOS 5.8'|'SunOS 5.9')
     DATE=/opt/OSS/bin/date
     MAIL_APP=/usr/bin/mailx
     PS_CMD="/usr/ucb/ps axww";;
  Linux*)
     DATE=date
     MAIL_APP=mail
     PS_CMD="ps axww"
     LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/openpkg/lib32
     export LD_LIBRARY_PATH;;
  *) echo "unsupported OS [$SYS]"
     exit 1;;
esac

#
# ##############################################################################
#
# process command line arguments
#
USAGE="usage: $0 -p program -c config_file -l logdir [-o oper] [-h hostname] [-s log_string] [-u username]"
#
# initialize values
#
PROGRAM=
CONFIG_FILE=
HOSTNAME=
LOG_DIR=
OPER=
LOGSTRING=
USERNAME=
#
# process command line arguments
#

while getopts p:c:h:l:o:s:u: OPTION
do
  case $OPTION in
    p)  PROGRAM="$OPTARG";;
    c)  CONFIG_FILE="$OPTARG";;
    h)  HOSTNAME="$OPTARG";;
    l)  LOG_DIR="$OPTARG";;
    o)  OPER="$OPTARG";;
    s)  LOGSTRING="$OPTARG";;
    u)  USERNAME="$OPTARG";;
   \?)  echo "not a valid option"
        echo "$USAGE"
        exit 1;;
  esac
done
#
# verify that required args are set
#
if [ -z "$PROGRAM" ]; then
    echo "$USAGE"
    exit 1
fi
if [ -z "$CONFIG_FILE" ]; then
    echo "$USAGE"
    exit 1
fi
if [ -z "$LOG_DIR" ]; then
    echo "$USAGE"
    exit 1
fi

#
# ##############################################################################
#
# this is the maximum time that the start script will sleep between successive 
# restarts of the cd tool. Full descripition is given above
#
MAX_WAIT_TIME=1920
#
#
# ##############################################################################
#
# Variables which should be the same at all sites
#
SCRIPT_CSC=ctbt.acquisition
#
# Derived variables
#
THIS_USER=$LOGNAME
SCRIPT_NAME=`basename $0`
PROGRAM_NAME=`basename $PROGRAM`
#
# ##############################################################################
#
# adjust environment. There may be a need to adjust the environment to make
# the PROGRAM run. This "environment adjustment" is done here.
# As some sites this step may not be needed. At other sites, sourcing the
# /etc/profile may be what is needed. This is the default behavior.
# At other sites there may be a need to explicitly set the LD_LIBRARY_PATH.
# Setting LD_LIBRARY_PATH is commented out by default (see below).
#
adjust_environment()
{
# source /etc/profile if it exists, since it may be needed to set
# LD_LIBRARY_PATH correctly
#
if [ -r "/etc/profile" ]; then
    . /etc/profile > /dev/null 2>&1
fi
#
# set umask so log file will have the permission of -rw-r--r--
# This must be done after ". /etc/profile", which may also set the umask.
#
umask 022
}
#
# ##############################################################################
#
# check_instance. Check if another instance of the cd tool and config file are
# running on this machine. This is checked using ps command. If there is another
# instance, exit with a fatal error.
#
check_instance()
{
RUNNING=`$PS_CMD | grep $PROGRAM | grep $CONFIG_FILE | grep -v $0 | grep -v grep | wc -l`
#
# $RUNNING should 1, which is this instance of the script itself.
# if $RUNNING is > 1, then report what else is running, and exit.
#
if [ $RUNNING -gt 0 ]
then
    msg="Fatal error: Program already running with config file: $PROGRAM : $CONFIG_FILE"
    echo $msg
    logger -i -p user.error -t $SCRIPT_CSC.$SCRIPT_NAME $msg
    if [ ! -z "$OPER" ]; then
        $MAIL_APP -s "$msg" $OPER < /dev/null
    fi
    $PS_CMD | grep $PROGRAM | grep $CONFIG_FILE
    exit 3
fi
}
#
# ##############################################################################
#
#
# check_host_and_user. Make sure that the script is running on the proper host
# by the proper user. Note that both checks are optional, and the default is
# not to check either of these.
#
check_host_and_user()
{
#
# if $HOSTNAME is not given, skip this check
if [ ! -z "$HOSTNAME" ]
then
    THISHOST=`hostname`;

    if [ "$HOSTNAME" != "$THISHOST" ]
    then
        msg="Fatal error: script must run on host: $HOSTNAME  Currently on host $THISHOST"
        echo $msg
        logger -i -p user.error -t $SCRIPT_CSC.$SCRIPT_NAME $msg
        if [ ! -z "$OPER" ]; then
            $MAIL_APP -s "$msg" $OPER < /dev/null
        fi
        exit 2
    fi
fi
#
# if $USERNAME is not given, skip this check
if [ ! -z "$USERNAME" ]
then
    THISUSER=`whoami`;

    if [ "$USERNAME" != "$THISUSER" ]
    then
        msg="Fatal error: script must run by user: $USERNAME  Currently run by user $THISUSER"
        echo $msg
        logger -i -p user.error -t $SCRIPT_CSC.$SCRIPT_NAME $msg
        if [ ! -z "$OPER" ]; then
            $MAIL_APP -s "$msg" $OPER < /dev/null
        fi
        exit 2
    fi
fi

}
# ##############################################################################
#
# sanity checks. Make sure that we can run the PROGRAM, write to the LOG_DIR,
# and read the CONFIG_FILE.  Print error message to syslog and send message to
# OPER if any problem is encountered and exit.
#
sanity_checks()
{
#
# check that PROGRAM exists and is executable
#
if [ ! -x "$PROGRAM" ]
then
    msg="Fatal error: program cannot be run: $PROGRAM"
    echo $msg
    logger -i -p user.error -t $SCRIPT_CSC.$SCRIPT_NAME $msg
    if [ ! -z "$OPER" ]; then
        $MAIL_APP -s "$msg" $OPER < /dev/null
    fi
    exit 2
fi
#
# check that $LOG_DIR exists and is writable
#
if [ ! -w "$LOG_DIR" ]
then
    msg="Fatal error: cannot write to log directory: $LOG_DIR"
    echo $msg
    logger -i -p user.error -t $SCRIPT_CSC.$SCRIPT_NAME $msg
    if [ ! -z "$OPER" ]; then
        $MAIL_APP -s "$msg" $OPER < /dev/null
    fi
    exit 2
fi
#
# check that $CONFIG_FILE exists and is readable
#
if [ ! -r "$CONFIG_FILE" ]
then
    msg="Fatal error: config file could not be read: $CONFIG_FILE"
    echo $msg
    logger -i -p user.error -t $SCRIPT_CSC.$SCRIPT_NAME $msg
    if [ ! -z "$OPER" ]; then
        $MAIL_APP -s "$msg" $OPER < /dev/null
    fi
    exit 2
fi
}
#
# ##############################################################################
#
# Main program starts here
#
# adjust environment as needed to set LD_LIBRARY_PATH
#
adjust_environment
#
# check for another instance of this script
#
check_instance
#
# check for proper host and user
#
check_host_and_user
#
# check that proper files exist with the correct permissions
#
sanity_checks
#
# extract port number from the config file
#
PORT=`sed -n -e 's/^port=//p' < $CONFIG_FILE`
#
# if LOGSTRING is given, then add it to the log file name
#
if [ ! -z "$LOGSTRING" ]
then
    LOG_FILE=$PROGRAM_NAME.$PORT.$LOGSTRING.$$.log
else
    LOG_FILE=$PROGRAM_NAME.$PORT.$$.log
fi
#
# remove the logfile in the unlikely event it already exists
#
if [ -r "$LOG_FILE" ]
then
    rm -f "$LOG_FILE"
fi

#
# Initialise wait_sec to 30
#
wait_sec=30
#
# Initialise the current mode to stable (running without problems)
#
is_stable=1
#
# Initialise initial debug level to zero
#
DEBUG_LEVEL=0
export DEBUG_LEVEL

while true
do
    #
    # try to start $PROGRAM_NAME
    #
    START_DATE=`$DATE -u '+%Y/%m/%d %H:%M'`
    START_EPOCH=`$DATE -u '+%s'`
    #
    # Just before starting, log in syslog and send a message to $OPER
    #
    msg="$PROGRAM_NAME (port $PORT) started at $START_DATE"
    logger -i -p user.info -t $SCRIPT_CSC.$SCRIPT_NAME "$msg"
    if [ ! -z "$OPER" ]; then
            $MAIL_APP -s "$msg" $OPER < /dev/null
    fi
    #
    $PROGRAM $CONFIG_FILE >> $LOG_DIR/$LOG_FILE 2>&1
    #
    END_DATE=`$DATE -u '+%Y/%m/%d %H:%M'`
    END_EPOCH=`$DATE -u '+%s'`
    RUN_SEC=`expr $END_EPOCH - $START_EPOCH`
    #
    # program terminated, log in syslog and send a message to $OPER
    #
    msg="$PROGRAM_NAME (port $PORT) terminated at $END_DATE"
    logger -i -p user.info -t $SCRIPT_CSC.$SCRIPT_NAME "$msg"
    if [ ! -z "$OPER" ]; then
        $MAIL_APP -s "$msg" $OPER < /dev/null
    fi
    #
    # Check if the CD Tool has stopped within 60 seconds of starting
    # In this case wait a while.
    #
    if [ $RUN_SEC -le 60 ]
    then
        #
        # if $wait_sec has not yet reached MAX_WAIT_TIME, double the 
        # value of $wait_sec
        #
        if [ $wait_sec -lt $MAX_WAIT_TIME ]; then
            wait_sec=`expr $wait_sec \* 2`
        fi
        #
        #
        wait_min=`expr $wait_sec / 60`
        msg="$PROGRAM_NAME (port $PORT) stopped $RUN_SEC seconds after starting, sleeping $wait_min minute(s) before restarting"
        logger -i -p user.info -t $SCRIPT_CSC.$SCRIPT_NAME "$msg"
        if [ ! -z "$OPER" ]; then
            $MAIL_APP -s "$msg" $OPER < /dev/null
        fi
        #
        # if this is the first stop within 60 seconds (after a period when 
        # the cdtool has been running for > 60 seconds) 
        # then increase the debug level to find out what went wrong
        # else reset the debug level to prevent the log file getting too big
        #
        if [ $is_stable -eq "1" ]; then
            DEBUG_LEVEL=5
        else
            DEBUG_LEVEL=0
        fi
        is_stable=0
        #
        sleep $wait_sec
    else 
    #
    # This is a "normal" restart, since the CD tool ran for more than 60 seconds.
    # wait one minute to give the admin time to install a new
    # version of the CD Tool before trying to re-start :-)
    #
        sleep 60
        #
        # cdtool probably working normally, therefore reset the debug level
        #
        DEBUG_LEVEL=0
        is_stable=1
        #
        #        
        # reinitialize $wait_sec to 30
        #
        wait_sec=30
    fi
done

exit 0
