#################################################################################################
# .profile_sub_move		(c) R. H. Reepe 12th December 1996	Version 1.0		#
#################################################################################################
# 961212 RHR Genesis

#===========================================================================================
s_delete_account()		# (c) R. H. Reepe. Removes Account String and Audits
#===========================================================================================
# Arg_1 = [PID_Number]
{
	_pid=${1:-""}
	_audit_log=$ORACLE_LOG/oracle_audit_trail.log
	sleep 1
	rm -f $account_string"$_pid"
	_timestamp=`s_timestamp`
	echo "$_timestamp Audit Trail Cleanup for `s_prog`"	>> $_audit_log
	return 0
}


#===========================================================================================
s_access_account()		# (c) R. H. Reepe. Allowes accesses to Accounts and Audits
#===========================================================================================
# Arg_1 = Requested Account Name (coded string)
# Arg_2 = Calling Script Name ($0)
# Arg_3 = [Calling PID (for uniqueness)]
{

	_audit_log=$ORACLE_LOG/oracle_audit_trail.log
	if [ "$1" = "" ]
	then
		echo "Error in $0 : No coded string provided"
		echo "Oracle Connection Refused"
		exit 1
	fi
	if [ "$2" = "" ]
	then
		echo "Error in `s_prog` : No calling script_name provided for"
		echo "Subroutine s_access_account - Oracle Connection Refused"
		echo "Attempt to Crack Security made by $USER at `date`" >> $_audit_log
		echo "From terminal $TERM (`tty`) using script `s_prog`" >> $_audit_log
		exit 2
	fi
	_pid=${3:-""}
	_timestamp=`s_timestamp`
	_script_type=`dirname $2`
	_script_type=`basename $_script_type`
	_script_name=`basename $2`
	if [ "$_script_type" = "." ]
	then
		_script_type=`pwd`
		_script_type=`basename $_script_type`
		_script_name=`s_prog`
	fi
	account=`/usr/5bin/echo "$1\c" | $DECODE`
	/usr/5bin/echo "export account"		>  $account_string"$_pid"
	/usr/5bin/echo "account=$account\c"	>> $account_string"$_pid"
	. $account_string"$_pid"
	_name=`echo "$account" | tr '/' ' ' | cut -f1-1 -d\ `
	echo "$_timestamp Oracle connecting as $_name from $_script_type $_script_name" >> 
$_audit_log
	s_delete_account $_pid & > /dev/null 2>&1
	return 0
}


#===========================================================================================
s_profs()			# (c) R. H. Reepe. Sends UNIX mail to a PROFS id 
#===========================================================================================
# Arg_1 = PROFS_ID
# Arg_2 = Mail_File
# Arg_3 = Mail_Title
{
	#_profs_id="ford!"${1}@gtwy.ford.com	# Old Format Address
	_profs_id=${1}@gw.ford.com		# New Format Address
	_mail_title=`echo "$@" | cut -f3- -d\ `
	_mail=/usr/ucb/mail
	if [ -f $2 ]
	then
		$_mail -s `s_join $_mail_title` $_profs_id  < $2 
	else
		echo "Mail File [$2] Does Not Exist!"
	fi
}

#===========================================================================================
s_execute_file_transfer()	# (c) J. Schloesser. FTP Subroutine
#===========================================================================================
# Decription:
# This subroutine will prepare temporary command files and fork
# the actual ftp process for the file transfer and a monitor
# process (tail -f) to grep and parse ftp log information into
# the general process log file 
#--------------------------------------------------------------------
# Usage: to be called with a minimum of 4 parameters
#        parameter 1      : filepointer to process log file
#        parameter 2      : connect command  "open hostname" 
#        parameter 3      : validate command "user userid password"
#        parameter 4 - xxx: ftp commands     "lcd ...; get ... etc."
#--------------------------------------------------------------------
# Arg_s.... See USAGE above
{

#------------------------------------------------------------
# validate number of arguments and process the first 3 arguments
#------------------------------------------------------------
if [ $# -lt 4 ]
then
    echo "Subroutine s_execute_file_transfer called with less the 4 parameters!"
    echo "Process terminated in subroutine s_execute_file_transfer!"
    exit
fi
_log=$1
_connect=$2
_account=$3

#------------------------------------------------------------
# cut parameter list
#------------------------------------------------------------
_number_ftp_commands_left=`expr $# - 3`
shift 3

#------------------------------------------------------------
# create some unique file pointers
#------------------------------------------------------------
_ftp_commands=/tmp/ftp_commands_$$
_ftp_log=/tmp/ftp_log_$$
_ftp_return_code=/tmp/ftp_return_code_$$
_nawk_script=/tmp/nawk_script_$$

#------------------------------------------------------------
# Create the ftp command file for the eldb download file
#------------------------------------------------------------
echo $_connect						 > $_ftp_commands
echo $_account						>> $_ftp_commands

#------------------------------------------------------------
# Process all parsed commands and append to ftp command file
#------------------------------------------------------------
until [ $_number_ftp_commands_left -eq 0 ] 
do
    echo $1						>> $_ftp_commands
    shift
    _number_ftp_commands_left=`expr $_number_ftp_commands_left - 1`
done
echo "bye"						>> $_ftp_commands

#------------------------------------------------------------
# lets generate the nawk script for the monitor process
#------------------------------------------------------------
echo "#!/bin/awk"				 	 > $_nawk_script
echo "function get_date()"				>> $_nawk_script
echo "{"						>> $_nawk_script
echo "\"date '+%d-%h-%y %H:%M:%S '\" | getline ;"	>> $_nawk_script
echo "  printf (\"%s\", \$0);"				>> $_nawk_script
echo "  close(\"date '+%d-%h-%y %H:%M:%S '\");"		>> $_nawk_script
echo "}"						>> $_nawk_script
echo "{"						>> $_nawk_script
echo "{line=\$0; get_date(); print line; }"		>> $_nawk_script
echo "}"						>> $_nawk_script

#------------------------------------------------------------
# general loop for restarting ftp and its monitor 6 times
#------------------------------------------------------------
_ftp_succeeded=false
_wait_for_retry=false
_no_ftp_attempts=0
_no_ftp_attempts=`expr $_no_ftp_attempts + 0`
while [ $_ftp_succeeded = "false" -a $_no_ftp_attempts -lt 6 ]
do
    _no_ftp_attempts=`expr $_no_ftp_attempts + 1`

#------------------------------------------------------------
# preset an unsuccessful ftp return code
#------------------------------------------------------------
    echo 1 > $_ftp_return_code

#------------------------------------------------------------
# start the ftp process
# call "s_verify_pid" with parameters $! and "ftp "
#------------------------------------------------------------
    echo "                   ************ FTP  SESSION  START *************"	>> $_log
    ( ftp -nv < $_ftp_commands > $_ftp_log 2>&1 ; echo $? > $_ftp_return_code ) &
    s_verify_pid $! "ftp "
    _ftp_pid=$?

#------------------------------------------------------------
# start the ftp monitor (greps ftp process output, adds a timestamp and writes the log file)
# call "s_verify_pid" with parameters $! and "tail"
#------------------------------------------------------------
    tail -100lf $_ftp_log | nawk -f $_nawk_script >> $_log &
    s_verify_pid $! "tail"
    _monitor_pid=$?

#------------------------------------------------------------
# check if ftp process is working, by checking the size of the log file
#------------------------------------------------------------
    sleep 2
    _log_length=`wc -c $_ftp_log | cut -c1-8`
    _log_length=`expr $_log_length + 0`
    _loop_count=0
    _loop_count=`expr $_loop_count + 0`
    while [ $_log_length -eq 0 -a $_loop_count -le 12 ]
    do
        sleep 5          
        echo `s_timestamp`FTP logfile is not growing, process seems to be stuck	>> $log
        _log_length=`wc -c $_ftp_log | cut -c1-8`
        _log_length=`expr $_log_length + 0`

#------------------------------------------------------------
# set flag "wait_for_retry" after waiting 1 minute
#------------------------------------------------------------
        if [ $_loop_count -eq 12 ]
        then
            _wait_for_retry=true
        fi
        _loop_count=`expr $_loop_count + 1`
    done

#------------------------------------------------------------
# either wait for retry or wait on completion of file transfer
#------------------------------------------------------------
    if [ $_wait_for_retry = "true" ]
    then

#------------------------------------------------------------
# kill ftp process and monitor process and retry in 10 minutes
#------------------------------------------------------------
        kill -9 $_ftp_pid 2>&1
        kill -9 $_monitor_pid 2>&1

#------------------------------------------------------------
# abort controlling process here if 6th attempt for file transfer still failed
#------------------------------------------------------------
        if [ $_no_ftp_attempts -eq 6 ]
        then
            echo `s_timestamp`Termination after 6 failed transfer attempts	>> $_log
            echo "                   Check host table, DNS service, network"	>> $_log
            echo "                   connection and status of target node!"	>> $_log
            echo "                   Irregular stop of interface process"	>> $_log
            echo "Termination after 6 failed transfer attempts"
            echo "Process aborted at `date`"
            exit
        fi
        echo `s_timestamp`FTP process is stuck, child process killed!		>> $_log
        echo `s_timestamp`Retrying in 10 minutes!				>> $_log
        sleep 600
    else

#------------------------------------------------------------
# kill the monitor, after ftp terminated successfully
#------------------------------------------------------------
        while [ `cat $_ftp_return_code` != "0" ] 
        do
            sleep 2
        done
        sleep 2
        kill -9 $_monitor_pid 2>&1
        _ftp_succeeded=true
    fi
done

#------------------------------------------------------------
# delete temporary files and return to calling script
#------------------------------------------------------------
rm -f $_ftp_commands $_ftp_log $_ftp_return_code $_nawk_script			 > /dev/null  2>&1
sleep 2
echo "                   ************** FTP  SESSION  END *************"	>> $_log
sleep 2
return
}

#===========================================================================================
s_verify_pid()			# (c) J. Schloesser. Verification of Process Id's
#===========================================================================================
# Decription:
# This subroutine verifies a process id, by incrementing a parsed
# process id pointer and looking for a particular command string
#-------------------------------------------------------------------------
# Usage: to be called with 2 parameters
#        parameter 1      : process id to start process table scan
#        parameter 2      : process command to search for in process table
#-------------------------------------------------------------------------
# Return Value:
# The subroutine returns a process id on success and the string
# "99999999999" upon failure. The kill command will then obviously fail!
#-------------------------------------------------------------------------
# Args - See Usage above
{
_pid=$1 
_actual_command=$2
_loop_count=0
#------------------------------------------------------------
# increase the pid (returned from fork "$!") until pid and command match a process table entry
#------------------------------------------------------------
while [ $_loop_count -le 10 ]
do
#------------------------------------------------------------
# additional grep $_pid in pipeline to filter out header line
#------------------------------------------------------------
    _loop_count=`expr $_loop_count + 1`
    _process_found_flag=`ps -fp $_pid | grep $_pid | cut -c48-53 | grep -c $_actual_command`
    if [ $_process_found_flag = "1" ]
    then
        return `echo $_pid`
    else
        _pid=`expr $_pid + 1`
    fi
done
echo "Subroutine s_verify_pid has not identified a correct process id"
echo "Pls check for an obsolete [$actual_command] process in the process table"
return 99999999999
}