#!/bin/ksh 

#
#@(#) File:    trace_kill9.sh
#@(#) Version: 1.0.0
#@(#) History: 
#@(#)     2015-11-17 : Roger Leuckie : Created
#

export sBaseDir="${0%/*}"
export sBaseName="${0##*/}"
if [ x"${sBaseDir}" = x"${sBaseName}" ] || [ x"${sBaseDir}"x = x"."x ]; then
        sBaseDir="${PWD}"
fi

export aTmpFiles[1]="${PWD}/${0}.${RANDOM}${RANDOM}.1.tmp"

export sREQUIREDuser="${sREQUIREDuser:-root}"
export sDEFAULTpump="${sDEFAULTpump:-/opt/javatools/scripts/pdump.sh}"
export iMinGB=${iMinGB:-3}

export sOUTPUTfile="${sBaseDir}/${sBaseName}.log"

export sCompleteFile="completed"

export aTimeStamp[1]="$( date +"%02m-%02d" )"
export aTimeStamp[2]="$( date +"%s" )"

export bYesToAll=

fShowVersion() {
	what ${0}
	fCleanupAndExit 0
}

fShowLicense() {
cat << END_OF_LICENSE
----------------------------------------------
 IBM International Program License Agreement
----------------------------------------------

 Part 1 - General Terms
 -----------------------

 PLEASE READ THIS AGREEMENT CAREFULLY BEFORE USING THE PROGRAM. IBM WILL
 ONLY LICENSE THE PROGRAM TO YOU IF YOU FIRST ACCEPT THE TERMS OF THIS
 AGREEMENT BY USING THE PROGRAM. IF YOU DO NOT AGREE TO THE TERMS OF THIS
 AGREEMENT, PROMPTLY NOTIFY THE PROVIDER OF THE PROGRAM AND REQUEST A
 REFUND OF THE AMOUNT YOU PAID.

 The Program is owned by International Business Machines Corporation or
 one of its subsidiaries (IBM) or an IBM supplier, and is copyrighted and
 licensed, not sold.

 IBM grants you a nonexclusive license for the Program. If IBM grants you
 multiple licenses for the Program, the terms of this Agreement apply to
 each license. The term "Program" means the original program and all
 whole or partial copies of it, including portions merged into other
 programs. A Program consists of machine-readable instructions,
 audio/visual content (such as images, text, recordings, or pictures), and
 related licensed materials.

 This Agreement includes Part 1 - General Terms and Part 2 - Country
 Unique Terms. The terms of Part 2 may replace or modify those of Part 1.
 "License Information," which IBM provides for the Program, may contain
 additional terms regarding the Program. Any such additional terms are
 part of this Agreement.
 
 1. License

 Use of the Program

 You may use the Program on only one machine at any one time, except as
 otherwise stated in this section. You agree to ensure that anyone who
 uses the Program (accessed either locally or remotely) does so only for
 your authorized use and complies with the terms of this Agreement.
 A Program is considered to be in use when it resides in memory or is
 otherwise stored on a machine. A Program stored on a network server
 solely for the purpose of being distributed to other machines is not
 considered to be in use.

 IBM specifies charges for Programs based on how much you use a Program
 (for example, the number of users), resources (for example, processor
 size), or a combination of both.

 For a Program managed by a license management tool, copies may be made
 and stored on machines under control of that tool, but your use may not
 exceed the total number of users or amount of resource authorized.
 Certain Programs IBM designates for home or travel use may be stored on
 the primary and another machine, provided the Program is not in active
 use on both machines at the same time.

 You may 1) copy the Program for backup and 2) merge the Program into
 another program. You must reproduce the copyright notice and any other
 legend of ownership on each copy, or partial copy, of the Program. You
 may use any portion of the Program IBM marks restricted (for example,
 "Restricted Materials of IBM") only to 1) resolve problems related to the
 use of the Program and 2) modify the Program so that it will work
 together with other products.

 You may not: 1) use, copy, merge, or transfer the Program except as
 provided in this Agreement; 2) reverse assemble, reverse compile, or
 otherwise translate the Program except as specifically permitted by law
 without the possibility of contractual waiver; or 3) sublicense, rent or
 lease the Program.
 
 Transfer of Rights and Obligations
 You may transfer all your rights and obligations under a license for a
 Program to another party, unless IBM specifies otherwise in its License
 Information.

 To transfer such rights and obligations, you must transfer a copy of this
 Agreement, the License Information, all other documentation (including
 proof of entitlement), and at least one complete, unaltered copy of the
 Program to the other party. Your license is then terminated.
 A Program which IBM licenses in multiples of two or more (for example, as
 a pack) may only be transferred in its entirety. In this case,
 individual licenses may not be transferred.
 
 2. Charges, Payment, and Taxes

 Payment must be made to the party (either IBM or its reseller) from whom
 you acquired the Program. If you acquired the Program from IBM, you
 agree to pay as IBM specifies. If any authority imposes a duty, tax,
 levy or fee (excluding those based on IBM's net income) on the Program
 supplied by IBM under this Agreement, you agree to pay that amount as IBM
 specifies or supply appropriate exemption documentation.
 You agree to notify IBM or its reseller and pay any applicable charges if
 you change the number of users or amount of resource authorized. IBM
 does not give refunds or credits for charges already due or paid.
 
 3. Limited Warranty

 For certain Programs IBM warrants that when they are used in the
 specified operating environment they will conform to their
 specifications. IBM does not warrant uninterrupted or error-free
 operation of a Program. The warranty period for a Program expires when
 its Program services are no longer available. IBM will specify in its
 License Information if a Program is warranted or not warranted.
 During the warranty period warranty service is provided, without charge,
 through defect-related Program services. Program services are available
 for at least one year following a Program's general availability.
 Therefore, the duration of warranty service depends on when you obtain
 your license. If a Program does not function as warranted during the
 first year after you obtain your license and IBM is unable to make it do
 so, you may return the Program to the party (either IBM or its reseller)
 from whom you acquired it and your money will be refunded. To be
 eligible, you must have acquired the Program while Program services
 (regardless of the remaining duration) were available for it.
 THESE WARRANTIES REPLACE ALL OTHER WARRANTIES OR CONDITIONS, EXPRESS OR
 IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR
 CONDITIONS OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 These warranties give you specific legal rights, and you may also have
 other rights which vary from jurisdiction to jurisdiction. Some
 jurisdictions do not allow the exclusion or limitation of implied
 warranties, so the above exclusion or limitation may not apply to you.
 In that event such warranties are limited in duration to the warranty
 period. No warranties apply after that period.

 4. Program Services

 Defect-related Program services are provided for warranted Programs and
 for selected other Programs. If your reported problem can be reproduced
 in the specified operating environment, defect correction information, a
 restriction or a bypass will be issued. Program services are provided
 only for the unmodified portion of a current release of a Program.
 Information regarding how you may obtain Program services will be
 provided by the party (either IBM or its reseller) from whom you acquired
 the Program. The duration of Program services is specified in the
 License Information.

 5. Patents and Copyrights

 If a third party claims that a Program IBM provides to you infringes that
 party's patent or copyright, IBM will, at its expense, defend you against
 that claim and pay all costs, damages, and attorney's fees that a court
 finally awards, provided that you 1) promptly notify IBM in writing of
 the claim and 2) allow IBM to control, and cooperate with IBM in, the
 defense and any related settlement negotiations. If such a claim is made
 or appears likely to be made, you agree to permit IBM to enable you to
 continue to use the Program, or to modify it, or replace it with one that
 is at least functionally equivalent. If IBM determines that none of
 these alternatives is reasonably available, you agree to return the
 Program to IBM on IBM's written request. IBM will then give you a credit
 for a one-time charge Program, provided its total charges have been fully
 paid. This is IBM's entire obligation to you regarding any claim of
 infringement. IBM has no obligation regarding any claim based on any of
 the following: 1) your modification of a Program; 2) the combination,
 operation, or use of a Program with any programs, data, or apparatus that
 IBM did not provide; or 3) infringement by a non-IBM Program.

 6. Limitation of Liability

 Regardless of the basis on which you may be entitled to recover damages
 from IBM, for any claim (including fundamental breach, negligence,
 misrepresentation or other tort), IBM's liability will only be for 1)
 payments referred to in the patents and copyrights terms described above;
 2) bodily injury (including death), and damage to real property and
 tangible personal property; and 3) the amount of any other actual direct
 damages or loss, up to the greater of the equivalent of U.S. $100,000 in
 your local currency or IBM's then generally available license charge for
 the Program.

 IBM WILL NOT BE LIABLE FOR ANY SPECIAL, INCIDENTAL, OR INDIRECT DAMAGES
 OR FOR ANY ECONOMIC CONSEQUENTIAL DAMAGES (INCLUDING LOST PROFITS OR
 SAVINGS), EVEN IF IBM, OR ITS RESELLER, HAS BEEN ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT ALLOW THE
 EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE
 ABOVE LIMITATION OR EXCLUSION MAY NOT APPLY TO YOU.

 IBM will not be liable for 1) loss of, or damage to, your records or data
 or 2) any damages claimed by you based on any third party claim.
 This limitation of liability also applies to any developer of a Program
 supplied to IBM. It is the maximum for which we are collectively
 responsible.

 7. General

 You may terminate your license at any time. If you do so, all your
 license rights to the Program are terminated. You may keep a copy of the
 Program in your archives. IBM may terminate your license if you fail to
 comply with the terms of this Agreement. If IBM does so, all your
 license rights to the Program are terminated and you must destroy all
 your copies of it.
 You agree to comply with all applicable export laws and regulations.
 Neither party may bring a legal action under this Agreement more than two
 years after the cause of action arose.
 This Agreement is governed by the laws of the country in which you
 acquired the Program.
 
 -------------------------------------------------------------------------
 IBM International Program License Agreement
 Part 2 - Country Unique Terms
 -------------------------------------------------------------------------

 AUSTRALIA: Limited Warranty (Section 3): The warranties specified this
 Section are in addition to any rights you may have under the Trade
 Practices Act or other legislation and are only limited to the extent
 permitted by the applicable legislation.
 Limitation of Liability (Section 6): The following paragraph is added to
 this Section:
 Where IBM is in breach of a condition or warranty implied by the Trade
 Practices Act 1974, IBM's liability is limited to: (a) where IBM
 supplied services - the cost of having the services supplied again; or
 (b) where IBM supplied goods - the repair or replacement of the goods, or
 the supply of equivalent goods. Where that condition or warranty relates
 to right to sell, quiet possession or clear title, or the goods are of a
 kind ordinarily acquired for personal, domestic or household use or
 consumption, then none of the limitations in this paragraph apply.

 CANADA: General (Section 7): This Agreement is governed by the laws of
 the Province of Ontario.

 CENTRAL EUROPE & RUSSIA: General (Section 7): This Agreement is governed
 by the material laws of Austria. All disputes and controversies between
 the parties arising out of, or in connection with, this Agreement or its
 implementation, performance or interpretation, shall be finally settled
 under the Rules of Arbitration and Reconciliation of the Arbitral Centre
 of the Federal Economic Chamber in Vienna (Vienna Rules), by three
 arbitrators appointed in accordance with said Rules. The arbitration
 shall be held in Vienna, Austria. The official language of the
 proceedings shall be English. The decision of the arbitrators shall be
 final and binding upon both parties and therefore, the parties pursuant
 to paragraph 598(2) of the Austrian Code of Civil Procedure, expressly
 waive the application of paragraph 595(1), figure 7 of said Code. The
 clauses set forth above shall, however, in no way limit our right to
 institute proceedings in any competent court.

 ESTONIA, LATVIA, LITHUANIA: General (Section 7): All disputes arising in
 connection with the present Agreement shall be finally settled in
 Arbitration. Each party shall appoint one arbitrator and they shall
 jointly appoint the chairman. If they cannot agree on the chairman, then
 the chairman shall be appointed by the Central Chamber of Commerce in
 Helsinki. In the Arbitration the law on Arbitration will be adhered to.
 Finnish law shall apply. The arbitrators shall come together in
 Helsinki.

 GERMANY, AUSTRIA, SWITZERLAND: Limited Warranty (Section 3): The
 warranty for an IBM Program covers the functionality of the Program for
 its normal use. In case a Program is delivered without specifications,
 IBM will only warrant that the Program information correctly describes
 the Program and that the Program can be used according to the Program
 information. In case non-IBM Programs are contracted by IBM and
 delivered by IBM, the warranty for IBM Programs is applicable unless
 otherwise agreed in a transaction document. Warranty service for non-IBM
 Programs may be performed by non-IBM manufacturers.
 Limitation of Liability (Section 6): The limitations and exclusions
 specified in the Agreement will not apply to damages caused by us with
 intention or gross negligence. IBM is liable for assured
 characteristics.
 General (Section 7): The limitation on bringing a legal action is not
 applicable in case of tort by either IBM or you, or our agents.

 ISRAEL: General (Section 7): The limitation on bringing a legal action
 will be according to the law of limitation provided a notification
 concerning the cause of action was sent no more than two years after the
 cause of action arose or became known to plaintiff.

 IRELAND: Limited Warranty (Section 3): No statement in this Agreement
 shall affect the statutory rights of consumers.
 
 MIDDLE EASTERN COUNTRIES: ABU-DHABI(UAE), BAHRAIN, DUBAI(UAE), OMAN,
 KUWAIT, QATAR
 General (Section 7): This Agreement is governed by the law and
 jurisdiction of Bahrain.

 NEW ZEALAND: Limited Warranty (Section 3): The warranties specified in
 this Section are in addition to any rights you may have under the
 Consumers Guarantee Act 1993 or other legislation which cannot be
 excluded or limited. The Consumer Guarantees Act 1993 will not apply in
 respect of any goods or services which IBM provides, if you require the
 goods or services for the purposes of a business as defined in that Act.
 Limitation of Liability (Section 6): The following paragraph should be
 added to this Section:
 Where products or services are not acquired for the purposes of a
 business as defined in the Consumer Guarantees Act 1993, the limitations
 in this Section are subject to the limitations in that Act.

 PEOPLE'S REPUBLIC OF CHINA: Charges, Payment, and Taxes (Section 2): All
 banking charges incurred in the People's Republic of China shall be borne
 by you and those incurred outside the People's Republic of China shall be
 borne by us.
 General (Section 7): The laws of the State of New York govern this
 Agreement. Any dispute concerning this Agreement may be settled by
 arbitration. The arbitration will take place in Stockholm, Sweden, under
 the auspices of the International Arbitration Center in English in
 accordance with the rules then in effect under the United Nations
 Commission on International Trade Law (UNCITRAL). The arbitration award
 will be final and binding on both parties and both parties shall act
 accordingly. The arbitration fee shall be borne by the losing party.

 UNITED KINGDOM: Limitation of Liability (Section 6): Add the following
 paragraph at the end of the first paragraph:
 The limitation of liability shall not apply to any breach of IBM's
 obligations implied by Section 12 of the Sales of Goods Act 1979 or
 Section 2 of the Supply of Goods and Services Act 1982.

 UNITED STATES OF AMERICA: General (Section 7): This Agreement is
 governed by the laws of the State of New York.
 
 
 -------------------------------------------------------------------------
 Part 3 - License Information for "IBM AIX Java Diagnostic Tools"
	  ( pdump.sh, libsGrabber.sh, dbxpth.sh, javaenv, dbxtrace.sh )
 -------------------------------------------------------------------------
 
   THIS PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EX-
   PRESS   OR   IMPLIED,   INCLUDING   THE   IMPLIED   WARRANTIES   OF
   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  IBM does not
   warrant uninterrupted or error free operation of  the  Program,  or
   that the Program is free from claims by a third party of copyright,
   patent, trademark, trade secret, or any other intellectual property
   infringement.    IBM  has  no obligation to provide service, defect
   correction, or any maintenance for the Program. IBM  has  no  obli-
   gation to supply any Program updates or enhancements to you even if
   such are or later become available.
 
   Under no circumstances is IBM liable for any of the following:
 
   1.  third-party claims against you for losses or damages;
   2.  loss of, or damage to, your records or data; or
   3.  direct  damages,  lost  profits, lost savings, incidental, spe-
       cial, or indirect damages or other consequential damages,  even
       if IBM or its authorized supplier, has been advised of the pos-
       sibility of such damages.
 
   Some jurisdictions do not allow these limitations or exclusions, so
   they may not apply to you.
END_OF_LICENSE

	fCleanupAndExit 0

}

fUsage() {

	{
	if (( ${#} == 2 )); then
		echo
		echo "[ ${1} ] ${2}"
	fi
	echo
	echo "[ USAGE ] ${sBaseName} -j JAVA_PID -p FULL_PMR [ -P FULL_PATH_TO_PDUMP ] [ -d WORK_DIRECTORY ] [ -o OUTPUT_FILE ] [ -s ] [ -y ] | -h | -v | -l"
	echo
	echo "[ REQUIREMENT ] This script can only be executed by the '${sREQUIREDuser:-root}' user"
	echo "[ REQUIREMENT ] JAVA_PID must be active and valid 'java' process id (see 'ps' command)"
	echo "			Use -s to skip the confirmation that the process name contains 'java'"
	echo "[ REQUIREMENT ] WORK_DIRECTORY must exist and have at least ${iMinGB:-3} GB of free space"
	echo "			WORK_DIRECTORY defaults to the current directory"
	echo "[ REQUIREMENT ] FULL_PMR must be your active and valid PMR# and in the format #####,###,###"
	echo "[ REQUIREMENT ] FULL_PATH_TO_PDUMP was be set to the full path to the 'pdump' script"
	echo "			FULL_PATH_TO_PDUMP defaults to ${sDEFAULTpump:-/opt/javatools/scripts/pdump.sh}"
	echo "			Download pdump.sh from the URL: ftp://ftp.software.ibm.com/aix/tools/debug/pdump.sh"
	echo "			Use '-P SKIP' to skip the execution of pdump.sh"
	echo
	} >&2
	
	fCleanupAndExit 1

}

fValidateJAVApid() {
	typeset -u sConfirm

	if [ -z "${iJAVApid}" ]; then
		fUsage "ERROR" "No Java process id (PID) specified"
	fi

	ps -ef > "${aTmpFiles[1]}"

	bMatched="$( awk 'BEGIN{a="no_match"} (( iPID == $2) && ( bMatchJava == 0)) { a="match"} (( iPID == $2) && ( bMatchJava) && ( $0 ~ "java")) { a="match" } END{ print a}' iPID="${iJAVApid:-AAAA}" bMatchJava=${bMatchJava} "${aTmpFiles[1]}" 2>/dev/null )"

	if [ x"${bMatched:-no_match}"x = x"no_match"x ]; then
		fUsage "ERROR" "The Java process specified (${iJAVApid}) was not listed in 'ps' output and/or did not match 'java' process name"
	fi

	echo
	echo "[ INFO ] JAVA_PID= ${iJAVApid}"
	echo "[ INFO ] PROCESS_NAME= $( awk '( pid == $2) {print $0}' pid=${iJAVApid} "${aTmpFiles[1]}" \
			| sed -e "s|.* [0-9][0-9]*:[0-9][0-9] *||g" \
			| awk '{print $1}')"
	if [ -z "${bYesToAll}" ]; then
		echo "[ CONFIRM ] Press 'Y' (uppercase) key, then the 'ENTER' key to continue [Y] \c"; read sConfirm
		if [ x"${sConfirm:-n}"x != x"Y"x ]; then
			fCleanupAndExit 1 "[ INFO ] User did not press 'Y' (uppercase) to confirm. This script is exiting."
		fi	
	fi

	echo "[ INFO ] JAVA_PID has been confirmed by the user"

	return
}

fValidateFULLpmr() {

	if [ -z "${sFULLpmr}" ]; then
		fUsage "ERROR" "No PMR was specified. Re-read the instructions and try again."
	elif (( ${#sFULLpmr} != 13 )); then
		fUsage "ERROR" "The PMR# is not in the correct format (${sFULLpmr} != #####,###,###). Re-read the instructions and try again."
	else
		export IIFS="${IFS}"
		export IFS=",."
		set -f ${sFULLpmr}
		if  (( ${#} != 3 )) && (( ${#1} != 5 )) && (( ${#2} != 3 )) && (( ${#3} != 3 )); then
			export IFS="${IIFS}"
			fUsage "ERROR" "The PMR# is not in the correct format (${sFULLpmr} != #####,###,###). Re-read the instructions and try again."
		fi
		export IFS="${IIFS}"
		export sFULLpmr="${1}.${2}.${3}"
	fi

	echo "[ INFO ] FULL_PMR= ${sFULLpmr}"

	return 
}

fValidateWORKdir() {

	if [ ! -d "${sWORKdir:-NO_DIR_SPECIFIED}" ]; then
		fUsage "ERROR" "The WORK_DIRECTORY (${sWORKdir:--NO_DIR_SPECIFIED}) may not exist.  Re-read the instructions and try again."
	elif ! touch "${sWORKdir}/testfile" >/dev/null 2>&1; then
		fUsage "ERROR" "Unable to access the WORK_DIRECTORY (${sWORKdir:--NO_DIR_SPECIFIED}).  Re-read the instructions and try again."
	else
		rm -f "${sWORKdir}/testfile"
		iCurrentSize="$( df -km "${sWORKdir}" | tail -1 | awk '{print $3}' | cut -d. -f1 2>/dev/null )"
		(( iMinSize = ( iMinGB * 1024 ) ))

		if (( ${iCurrentSize:-99999999999} < iMinSize )); then
			fUsage "ERROR" "Not enough free space (${iCurrentSize:-error}(current MB) >= ${iMinSize}(minimum MB)) in WORK_DIRECTORY (${sWORKdir:--NO_DIR_SPECIFIED}).  Re-read the instructions and try again."
		fi
	fi

	echo "[ INFO ] WORK_DIRECTORY= ${sWORKdir} (free space= ${iCurrentSize} MB)"

	return 
}

fValidatePDUMPdir() {

	if [ x"${sPDUMPfile}"x = x"SKIP"x ]; then
		echo "[ INFO ] PDUMP will be skipped"
	elif [ ! -f "${sPDUMPfile:-NO_FILE_SPECIFIED}" ]; then
		fUsage "ERROR" "Unable to access the FULL_PATH_TO_PDUMP (${sPDUMPfile:-NO_FILE_SPECIFIED}).  Re-read the instructions and try again."
	else
		echo "[ INFO ] FULL_PATH_TO_PDUMP= ${sPDUMPfile}"
	fi

	return 
}

fCleanupAndExit() {

	if (( ${#} < 1 )); then
		iRC=0
	else
		iRC="${1:-0}"
		shift
	fi

	{
		if (( ${#} == 2 )); then
			echo
			echo "[ ${1} ] ${2}"
		fi

		echo
		echo "[ INFO ] Cleaning up temporary files ..."
		rm -f ${aTmpFiles[*]} >/dev/null 2>&1
		
		if [ -d "${sTMPdir:-NO_DIR_CREATED}" ] && [ ! -f "${sTMPdir}/${sCompleteFile}" ] && [ x"${sTMPdir}"x != x"/"x ]; then
			echo "[ INFO ] Cleaning up temporary directory: ${sTMPdir}"
			rm -fr "${sTMPdir}"
		fi
		echo
	} >&2

	exit ${iRC}
}

fValidateUSERid() {
	if [ x"${sUSERid}"x != x"${sREQUIREDuser:-root}"x ]; then
		fUsage "ERROR" "Must be logged in as '${sREQUIREDuser:-root}' to run this script. Logged in as '${sUSERid}'."
	fi
	return 
}

fCreateTMPdir() {

	sTMPdir="${sWORKdir}/PMR-${sFULLpmr}/${aTimeStamp[1]}/data"

	typeset -u sConfirm

	if [ -d "${sTMPdir:-NO_DIR_SPECIFIED}" ] && [ -z "${bYesToAll}" ]; then
		echo
		echo "[ CONFIRM ] The temporary work directory (${sTMPdir}) already exists."
		echo "[ CONFIRM ] Press 'Y' (uppercase) key, then the 'ENTER' key to continue to use this directory (files may be overwritten) [Y] \c"; read sConfirm
		if [ x"${sConfirm:-n}"x != x"Y"x ]; then
			fCleanupAndExit 1 "[ INFO ] User did not press 'Y' (uppercase) to confirm. This script is exiting."
		fi	
	fi

	if [ ! -d "${sTMPdir}" ]; then
		if ! mkdir -p "${sTMPdir}" >/dev/null 2>&1; then
			fCleanupAndExit 1 "ERROR" "Unable to create the temporary directory: ${sTMPdir}.  Check path and permissions and try again."
		fi
	fi

	echo "[ INFO ] Temporary work directory= ${sTMPdir}"
}

fCollectData() {
	typeset -u sConfirm
	echo

	if [ -z "${bYesToAll}" ]; then
		echo "[ CONFIRM ] Press 'Y' (uppercase) key, then the 'ENTER' key if you are ready to start the data collection procedures  [Y] \c"; read sConfirm
		if [ x"${sConfirm:-n}"x != x"Y"x ]; then
			fCleanupAndExit 1 "[ INFO ] User did not press 'Y' (uppercase) to confirm. This script is exiting."
		fi	
	fi

	cd "${sTMPdir}"

	echo
	echo "[ INFO ] Starting data collection ..."
	echo "[ INFO ] Current directory= ${PWD}"
	if [ x"${sPDUMPfile}"x != x"SKIP"x ]; then
		echo "[ INFO ] Starting: ${sPDUMPfile} ${iJAVApid}"
		${sPDUMPfile} ${iJAVApid}
	fi

	ps -ef > ps-ef.before
	ps avwwwwg > ps-avg.before

	
	echo "[ INFO ] Starting: kernel trace"
	trace -a -d -n -l -T268435184 -L536870368 -p -r PURR -o "trace.raw"
  	trcon

	echo "[ INFO ] Executing: kill -9 ${iJAVApid}"
	kill -9 ${iJAVApid}

	echo "[ INFO ] Stopping: kernel trace"
	trcstop
	
	if [ x"${sPDUMPfile}"x != x"SKIP"x ]; then
		echo "[ INFO ] Starting: ${sPDUMPfile} ${iJAVApid}"
		${sPDUMPfile} ${iJAVApid}
	fi

	ps -ef > ps-ef.after
	ps avwwwwg > ps-avg.after

	echo "[ INFO ] Post processing diagnostic data .. this may take several minutes ... please wait"
	trcrpt -r -o trace.rpt trace.raw
	trcnm > trcnm.out
	gennames > gennames.out
	cp /etc/trcfmt trace.fmt
	LDR_CNTRL=MAXDATA=0xB0000000@DSA gensyms > gensyms.out
	trcrpt -C all -n gennames.out -o trace.txt -O exec=on,timestamp=1,cpuid=on,pid=on,svc=on,tid=on -t trace.fmt trace.raw

	rm -f "core" >/dev/null 2>&1

	touch "${sCompleteFile}"

	cp "${sOUTPUTfile}" ./

	echo "[ INFO ] Packaging the diagnostic data ... this may take several minutes ... please wait"
	
	echo "[ INFO ] Current directory= ${PWD}"	
	cd "${sWORKdir}/PMR-${sFULLpmr}"

	sUPLOADfile="${sFULLpmr}.${aTimeStamp[1]}.${aTimeStamp[2]}.tgz"

	echo "[ INFO ] Creating upload file= ${sUPLOADfile}"	
	tar -cf - ${aTimeStamp[1]} | gzip -c > "${sUPLOADfile}"

	if [ -f "${sUPLOADfile}" ]; then
		echo
		echo "[ INFO ] ******************************************************************************"
		echo "[ INFO ] Please upload the file '${PWD}/${sUPLOADfile}' to your IBM PMR."
		echo
		echo "[ INFO ] Visit the web page: http://www-01.ibm.com/support/docview.wss?uid=isg3T1022619"
		echo "[ INFO ] for complete upload instructions"
		echo "[ INFO ] ******************************************************************************"
		echo
	else
		fCleanupAndExit 1 "ERROR" "The upload file (${sUPLOADfile}) was not created.  Please create it manually"
	
	fi
	
	
}


export iJAVApid=""
typeset -l sFULLpmr=""
export sFULLpmr
export sWORKdir="${PWD}"
export sPDUMPfile="${sDEFAULTpump:-/opt/javatools/scripts/pdump.sh}"
export bMatchJava=1
export sTMPdir=""

trap "fCleanupAndExit '1' 'INFO' 'Script interrupted by user'" 2 3

export sUSERid="$( id -un )"
fValidateUSERid

while getopts "j:p:d:P:o:hslvy" opt; do

	case "${opt:-h}" in

	"j" )	iJAVApid="${OPTARG}";;
	"p" )	sFULLpmr="${OPTARG}";;
	"d" )	sWORKdir="${OPTARG}";;
	"P" )	sPDUMPfile="${OPTARG}";;
	"s" ) 	bMatchJava=0;;
	"o" ) 	sOUTPUTfile="${OPTARG}";;
	"v" )	fShowVersion;;
	"l" )	fShowLicense;;
	"y" ) 	bYesToAll="y";;
	"h" ) 	fUsage ;;
		
	esac

done

{
fValidateFULLpmr
fValidateWORKdir
fValidatePDUMPdir
fValidateJAVApid

fCreateTMPdir

fCollectData

fCleanupAndExit 0
} 2>&1 | tee "${sOUTPUTfile}"
