#! /bin/bash

###
### This is demonstration code.  No warranty expressed or implied.
###
### Copyright (c) 2004, Martin Consulting Services, Inc.  Released to
### the public domain under the Lesser Gnu Public License
###


#
# cmdname - command description
#
# Usage: enter "command -h" or see Usage function immediately below.
#
#
#  $Log$
#
#



#
# Function Usage - display usage message.
#
function Usage
{

more >&2 <<ENDUSAGE
cmdname - command description

Usage: $Prog [-m mailid] [-e mailid] [-h] [-d] parameters

Options:
	-d		:	Diagnostics: display a diagnostic trace
	-e mailid	:	Error: send an execution report to this ID
				only if errors are detected.  May be
				repeated.
	-h		:	Help: display the usage panel
	-m mailid	:	Mail: send an execution report to this ID.
				May be repeated to send multiple reports.
	-t		:	Test: don't really run dangerous commands.
	-v		:	Verbose

Parameters:
	(none)

Return Codes:
	0		:	Normal termination
	1		:	Usage panel displayed in response to -h option
	2		:	Invalid option specified
	3		:	Required option argument missing
	4		:	Security exposure detected
	5		:	Unable to locate $Prog filter file.
	6		:	Unable to CD to base directory $RunDir.
	8		:	Unexpected message detected.
	
Notes:
	(none)

ENDUSAGE
}



#
# Function Sample - sample function skeleton
#
function Sample
{

typeset var			# Declare local variables

if $Trace
then
	set -xv
	PS4='[$LINENO]: '
fi
}





#
# Function RunJob - main code.
#
function RunJob
{

typeset var			# Declare local variables

if $Trace
then
	set -xv
	PS4='[$LINENO]: '
fi

echo "$Prog started $(date)"
echo "Command parameters: $CmdArgs" 

######################### Add main code here. ##########################


}



#
# Function RunDangerousCmd - run a command.  If $TestFlag is true, don't
#	run it, just display it.  If $Verbose is true, display the command.
#
function RunDangerousCmd
{

typeset var			# Declare local variables

if $Trace
then
	set -xv
	PS4='[$LINENO]: '
fi

if $TestFlag
then
	# We're in test mode.  Don't really run anything.
	echo "Testing: $*"
	return 0
else
	# This is for real.
	$Verbose && echo "Executing: $*"
	eval $*
	return $?
fi
}


# Mainline code - do job set-up.
#
# Set up environment, standard variables.
 
. /etc/profile > /dev/null
# . $HOME/.profile

Prog=${0##*/}
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/usr/bin:/etc:/bin:/usr/bin:/usr/ucb
BaseDir="$HOME/bin"			# Where I find my files.
RunDir="$HOME/bin"			# Where I should run.
LogFile="$BaseDir/$Prog.log"		# Detailed log file.
SummaryFile="/tmp/$Prog.$$.sum"		# Summary log file (temporary).
ErrorFlag="/tmp/$Prog.$$.err"		# Error indicator (temporary).
ValidOptions=":de:hm:tv"		# Valid command line options.
ConfigFile="$BaseDir/$Prog.cfg"		# Location of our configuration data.
AwkFile="$BaseDir/$Prog.filter"		# Location of our output filter.


# Put us in the right directory.
cd $RunDir
if [[ "$PWD" != "$RunDir" ]]
then
	echo "Unable to CD to $RunDir" 
	exit 6
fi

# Initialize our work files.  Go through some hoops to make sure no one else is
# trying to exploit our work files.
trap "rm -f $SummaryFile $ErrorFlag 2> /dev/null" EXIT
umask 077                                             # No one else can use
for Name in $LogFile $SummaryFile $ErrorFlag
do
	[[ -f $Name ]] && rm $Name			# Delete it if it exists
	cat /dev/null > $Name				# Create it, empty
	# Protect against race conditions/security exposure
	Line=`ls -l $Name | awk '{print $1, $3, $5}'`	# Get perms, user, size.
	Perms="${Line%% *}"				# Parse out the perms.
	Owner="${Line#* }"				# Parse out owner, stp 1
	Owner="${Owner% *}"				# Parse out owner, stp 2
	Size="${Line##* }"				# Parse out size
	if [[ ( "$Perms" != '-rw-------') || \
		("$Owner" != "$USER") || \
		($Size -ne 0) ]]
	then
		echo "Unexpected permissions ($Perms), owner ($Owner), or" \
			"data ($Size) in $Name -- aborting" >&2
		exit 4
	fi
done

# Set defaults
MailList=""		# Send an execution report to ...
ErrorList=""		# Send an execution report to ... if errors occur
Trace=false		# Assume we're not tracing.
TestFlag=false		# Assume we're running this for real.
Verbose=false		# Assume they don't want to see all the cmds.

# Get any defaults from the config file.
if [[ -r $ConfigFile ]]
then
	ConfigLine=`awk '/^ *ALLJOBS:/ {shift;print;exit}' $ConfigFile`
	# If we found anything, prepend it to our command line.  This
	# allows command line flags to override the config file.
	[[ -n $ConfigLine ]] && set -- ${ConfigLine#*:} $*
fi
CmdArgs="$*"

# Now process the job defaults and any override options.
while getopts "$ValidOptions" opt
do
	case $opt in
        d)      set -xv			# Turn on a Trace for the main Program.
		echo "Tracing $Prog..."	# Identify ourselves.
                PS4='[$LINENO]: '	# Include line numbers in trace.
		Trace=true;;		# Set flag so functions trace, too.
	h)	Usage			# Call the usage routine.
		exit 1;;
	e)	ErrorList="$ErrorList $OPTARG";;
	m)	MailList="$MailList $OPTARG"
		ErrorList="$ErrorList $OPTARG";;
	t)	TestFlag=true;;
	v)	Verbose=true;;
	\?)	# Invalid option.
		echo "$Prog: Unknown option \"-$OPTARG\".  " \
			"Enter \"$Prog -h\" for usage." >&2
		exit 2			# Exit with an error code.
		;;
	:)	# Option is missing parameter.
		echo "$Prog: Option \"-$OPTARG\" requires an argument." \
			"  Enter \"$Prog -h\" for usage." >&2
		exit 3			# Exit with an error code.
		;;
        esac
done
shift $((OPTIND-1))

# Run our process.  Log everything, then filter it and prepare a summary file.
RunJob "$@" 2>&1 |
	tee $LogFile |
	awk -vErrorFlag=$ErrorFlag -f $AwkFile |
	tee $SummaryFile

if [[ -s $ErrorFlag ]]
then
	rm $ErrorFlag
	echo "   $Prog ended with errors $(date)" | tee -a $SummaryFile
	[[ -n "$ErrorList" ]] && \
		(echo "The $Prog transfer failed with the following messages:"; cat $SummaryFile) |
			mail -s "$Prog $JobName $(date +%m/%d) log with errors" $ErrorList
	((ExitStatus=8))
else
	echo "   $Prog ended $(date)" | tee -a $SummaryFile
	[[ -n "$MailList" ]] && \
		mail -s "$Prog $JobName $(date +%m/%d) log" $MailList < $SummaryFile
	[[ -n "$NotifyList" ]] && \
		echo "The ODS \"$Prog $JobName\" transfer completed normally" | 
			mail -s "$Prog $JobName $(date +%m/%d) notification"
	((ExitStatus=0))
fi

exit $ExitStatus
