#!/usr/bin/ksh
#
# call_script.ksh - This is a script wrapper, used
# to call a main processing script, and will first
# make checks to see if the script is already running
#
#
#	Program calls: None
#								
#								
#	Input arguments:
#
# 	$1 = Name of script
#		$2 = Elapsed run time limit
#
#
# Creation Date:
#
#								7 April 2008 TimQuinn
#
#	Updates:
#					
#	

#
## Set the environment variables
#
#  . ${THMSOC}/src/config/soc_it_to_me.config
   . /home/thmsoc/astraea2_test/soc_it_to_me.config


#
## Grab input variable
#
	USAGE="usage: call_script.ksh [-t time_check] script_and_arguments"
	while getopts :t: arguments
  do
    case $arguments in
    t) time_check="$OPTARG";;
    \?) print "$OPTARG is not a valid switch."
        print "$USAGE";;
    esac
  done
  ((position_occupied_by_switches = OPTIND - 1))
  shift $position_occupied_by_switches

#
## Grab input script name and arguments
#
	n=0
	for arg in "$@"
	do
	  if (($n == 0))
		then
			script_name="$arg"
			if [[ -z $script_name ]]
			then
				echo "Please pass the name of a script......."
				exit 0
			fi
		else
			arg_list="${arg_list} $arg"
		fi
		n=$(( $n + 1 ))
	done

#
## Check input variables
#
	if [[ -z $time_check ]]
	then
		#set to default - 6 hours
		typeset -i time_check=21600
	else
		typeset -i time_check
	fi

#
## Set workstation variable
#
	workstation=$(uname -a |awk '{print $2}')

## Check if a process is currently running
#
	echo "$$:" >> $OVERLORDLOG
	echo "$$: Attempting to run script $script_name on $workstation....." >> $OVERLORDLOG
  prc_chk_astraea.ksh $script_name $time_check
	prcChk=$?
	if [[ $prcChk = "1" ]]
	then
		# script is running
		echo "$$:" >> $OVERLORDLOG
		echo "$$: Script $script is already running." >> $OVERLORDLOG
		echo "$$: Quitting........." >> $OVERLORDLOG
		exit 0
	else
		# signal script is not running so get it running......
		echo "$$: All clear - starting $script at $(date)." >> $OVERLORDLOG
		echo "$$: $script running........." >> $OVERLORDLOG
		startTime=$(date -u '+%Y-%m-%d %T')
		$script_name $arg_list
		stopTime=$(date -u '+%Y-%m-%d %T')
		echo "$$: $script complete at $(date)" >> $OVERLORDLOG
		process_log_test.php $script_name $workstation $startTime $stopTime
		exit 0
	fi