#!/bin/sh -xv
set -u  # force better programming and ability to use check for not set
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi
if [ "${1:-}" = "-q" ] ; then export quiet=1; shift; else quiet=0; fi

command="$@"
# fermi specific information
hypmail="hyp-enstore@hppc.fnal.gov"

node=`uname -n| sed -e 's/\([^\.]\)\..*/\1/'`
gang=`gang`

# sun nodes need an extended path in order to find all the regular unix commands
if [ `uname` = SunOS ]; then
  PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/lbin:/usr/ucb:/usr/ccs/bin
fi

start=`date +"%Y-%m-%d:%H:%M:%S"`
basename=`basename $0`
# sbin/$RCSfile$  $Revision$

# This is a derivative work, but it is still based on:

# Copyrighted as an unpublished work.
# (c) Copyright 1996,1997,1998 DESY Hamburg DMG-Division
# All rights reserved.

# RESTRICTED RIGHTS

# These programs are supplied under a license.  They may be used,
# disclosed, and/or copied only as permitted under such license
# agreement.  Any copy must contain the above copyright notice and
# this restricted rights notice.  Use, copying, and/or disclosure
# of the programs is strictly prohibited unless otherwise provided
# in the license agreement.

if test -w /dev/console -a $quiet -ne 1; then
  echo "$start: $0 $@ ...starting" >/dev/console
fi

tag=unknown

sendMail() {
  filename=$1
  mode=$2
  if [ "$mode" = "emergency" ] ; then
     mailaddress=$ENSTORE_MAIL
  else
     mailaddress=$ENSTORE_MAIL
  fi
  if [ -r $noMail ]; then
     mailaddress=$hypmail
  fi
  /usr/bin/Mail -s "$node ${3:-\"Enstore ecron Scheduler\"}" $mailaddress <$filename
  if test -w /dev/console -a $quiet -ne 1; then
     echo "`date`: $0 $@ has failed... sending mail to $mailaddress" >/dev/console
    echo < $filename >/dev/console
  fi
}

# pass in logit and tag
quit() {
  message="$1"
  code="$2"
  logit="$3"
  tag="$4"
  if [ -n "${message-}" ]; then echo "$1"; fi
  if [ "${5:-}" != "keepactive" ] ; then rmdir $activeFlag >/dev/null 2>&1; fi
  done=`date +"%Y-%m-%d:%H:%M:%S"`
  echo "$done $code" >> $histogram
  if test -w /dev/console -a $quiet -ne 1; then
    echo "$done: $0 $@ ...finished. code=$code" >/dev/console
  fi
  if [ -f $genAlarm -a $code != 0 ] ; then
      echo enstore alarm --raise --severity "A" --root-error "$command STAT=$code"
           enstore alarm --raise --severity "A" --root-error "$command STAT=$code"
  fi
  if [ "$logit" = "yes" ]
  then
      $ENSTORE_DIR/src/log_finish_event.py ${tag} $code
  fi
  exit $code
}

# May 12, 1999 Modified by huangch@fnal.gov to take arguments
#
# $0 [[-setup product] | [-D VARIABLE=value]]* cmd
#
# where product is any ups product that needs to be setup
#   and VARIABLE=value is an assignment of environmental variable
#
# product can be of the syntax with multiple products
#
# multiple -setup and -D are allowed

# May 13, 1999 Modified again to add -p job_name option
#
# $0 [[-setup product] | [-D VARIABLE=value] | [-p job_name] ]* cmd
#
# job_name is used to identify the job. If ommitted, cmd is default
# to ease the implementation, multiple -p are allowed, but only the
# last one is effective

# May 24, 1999 Modified again to add -d dir option
#
# $0 [[-setup product] | [-D VARIABLE=value] | [-p job_name] | [-d dir] ]* cmd
#
# dir is used to specify the current directory that the cmd is executed
# in. If ommitted, `pwd` is default. To ease the implementation,
# multiple -d are allowed, but only the last one is effective

# Sep 5, 2003 Modified again to add -c option
#
# $0 [[-setup product] | [-D VARIABLE=value] | [-p job_name] | [-d dir] | [-c error_count ]* cmd
#
# -c error_count will not sent out e-mail alert until contigous number
# of errors happened, as specified by error_count.
# if -c is omitted, -c 1 is assumed

# Feb 13, 2007 Modified again to add -need-enstore option
# with -need-enstore option, ecron will not execute if the enstore
# system is marked down

# Sep 26, 2007 Modified again to add -no-enstore option
# now -need-enstore is the default behavior
# -no-enstore is to supress it

# Sep 27, 2007 Modified again to add -no-log option
# logit=yes is defaul, -no-log overrides it.

# additional products

products=
job=
cwd=`pwd`
cntlimit=1
need_enstore="yes"
logit="yes"

while [ $1 = "-setup" ] || [ $1 = "-D" ] || [ $1 = "-p" ] || [ $1 = "-d" ] || [ $1 = "-l" ] || [ $1 = "-c" ] || [ $1 = "-need-enstore" ] || [ $1 = "-no-enstore" ] || [ $1 = "-no-log" ]
do
	case $1 in
	-setup)
		if [ -z "${products}" ]
		then
			products=$2
		else
			products=${products},$2
		fi
		shift
		;;
	-need-enstore)
		need_enstore="yes"
		;;
	-no-enstore)
		need_enstore="no"
		;;
	-D)
		var=`echo $2 | cut -f 1 -d '='`
		eval $2
		export $var
		shift
		;;
	-p)
		job=$2
		shift
		;;
	-d)
		cwd=$2
		shift
		;;
	-c)
		cntlimit=$2
		shift
		;;
	-l)
		logit="yes"
                ;;
	-no-log)
		logit="no"
		;;
	esac
	shift
done

cd $cwd		# to working directory

if [ -n "${job:-}" ]
then
	procName=${job}
else
	procName=$1
fi

log_name=${procName}

procInfos=$HOME/CRON/$procName
if [ ! -d $procInfos ]; then mkdir -p $procInfos; fi
activeFlag=${procInfos}ACTIVE
histogram=${procInfos}HISTOGRAM
procOutput=${procInfos}-output
procMail=${procInfos}-mail
noMail=${procInfos}NOMAIL
noNeg=${procInfos}NONEG
genAlarm=${procInfos}GENALARM
cntFile=${procInfos}.cnt
errcnt=0

if [ $# -eq 0 ] ; then quit "USAGE: $basename <enstoreName> <args ... >" -3 "$logit" "$tag"; fi

#read err count, if any
if [ -r $cntFile ]
then
	errcnt=`cat $cntFile`
fi

setup=/usr/local/etc/setups.sh
if [ ! -f $setup ] ; then quit "$setup not found" -4  "$logit" "$tag"; fi
. $setup
# should check that enstore was setup properly as well
setup enstore

# check if config server is running. If not, quit immediately
enstore config --alive --timeout 20
if [ $? -ne 0 ]
then
	echo "Configuration server is not running. Quit!"
	exit 0
fi

# log it?
if [ "$logit" = "yes" ]
then
	tag=`$ENSTORE_DIR/src/log_start_event.py ${log_name}`
fi

echo "$start 10" >> $histogram

#  check if a similar proc is already active
mkdir $activeFlag 1>/dev/null 2>/dev/null
if [ $? -ne 0 ] ; then
   if [ ! -f $noNeg ] ; then
      quit "" -2 "$logit" "$tag" "keepactive"
   else
      if [ "$logit" = "yes" ]
      then
	 $ENSTORE_DIR/src/log_finish_event.py ${tag} 0
      fi
      exit 0
   fi
fi


# setup additional products, if any

if [ -n "${products:-}" ]
then
 	setup ${products}
fi

# job is enabled and no other ones are still running.
# delete old output and old possible mail file
rm -f $procOutput
rm -f $procMail

# make sure procName is set to $1 again
procName=$1

shift

if [ "$need_enstore" = "yes" ]
then
	if [ "`enstore inq --is-up enstore`" = "yes" ]
	then
		echo  Executing: $procName $*
		eval $procName $*  >$procOutput 2>&1
		problem=$?
	else
		echo  Enstore is down
		problem=-3
	fi
else
	echo  Executing: $procName $*
	eval $procName $*  >$procOutput 2>&1
	problem=$?
fi

#if [ "$logit" = "yes" ]
#then
#	$ENSTORE_DIR/src/log_finish_event.py ${tag} ${problem}
#fi

# adjust the exit code so that it does not disappear off of the cron job plot
if [ $problem -gt 5 -o $problem -lt -5 ] ; then
   problem=7
fi

if [ $problem -ne 0 ] ; then
    let errcnt++
    echo "" >$procMail
    echo "  RC = $problem">>$procMail
    echo "  The Enstore ecron Scheduler found a problem running task !!! $procName $* !!! " >>$procMail
    echo "  Uname      :" `uname -a`  >>$procMail
    echo "  Date       :" `date`      >>$procMail
    echo "  Path       : $procName $* "  >>$procMail
    echo "  ReturnCode : $problem "   >>$procMail
    echo "  Working dir: $cwd "   >>$procMail
    echo "  Error count: $errcnt " >>$procMail
    echo "  Output and error messages ... " >>$procMail
    echo "  -------------------- start of messages ---------------------- ">>$procMail
    cat $procOutput >>$procMail 2>/dev/null
    echo "  -------------------- end of messages   ---------------------- ">>$procMail
    if [ $errcnt -ge $cntlimit ]
    then
        if [ $problem -ne -3 ] ; then
            sendMail $procMail emergency "ecron rc=$problem: $procName $* "
        fi
    fi
    # save the error output. we get python and ENSTORE_DIR from the enstore setup
    # the second parameter tells the script how many output files to keep.  the default
    # is 5
    python $ENSTORE_DIR/sbin/save_cron_output.py $procOutput 5
    echo $errcnt > $cntFile
else
    /bin/rm -rf $cntFile
fi

quit "" $problem  "$logit" "$tag"
