#! /bin/sh
# Generate a core dump from a running process, as used by the core_on_error=3
# run time tunable.
#
# Return codes:
#   0	Success
# 101	Bad command line
# 102	Invalid process id
# 103	Need to enable fullcore support
# 104	Not supported on this platform
# 105	Can not exec OS core dump command
# 106	Can not create core dump file
# o/w	As returned by gencore/gcore
#
# @(#)cobcore.app	7.1

# Check arguments
if test $# -eq 2
then
	COREFILE=$2
else
	if test $# -eq 1
	then
		COREFILE=core.$1
	else
		echo "Usage: $0 <pid> [filename]"
		exit 101
	fi
fi

PID=$1
export PID COREFILE

# Check that the first argument is a valid process id
kill -0 $PID 2> /dev/null
if test $? -ne 0
then
	echo "$0: No such process: $PID"
	exit 102
fi

# Generate core file, if supported
case `uname` in
	AIX)	STATUS=`lsattr -El sys0 | \
				sed -n -e "s/^fullcore *\([^ ]*\).*/\1/p"`
		if test ".$STATUS" != ".true"
		then
			echo "$0: Need to enable fullcore support: \c"
			echo "chdev -a fullcore=true -lsys0"
			exit 103
		fi
		exec gencore $PID $COREFILE
		exit 105
		;;
		
	Linux)	echo "$0: Can not generate a core dump from a running process"
		exit 104
		;;

	HP-UX)	echo "$0: Can not generate a core dump from a running process"
		exit 104
		;;
esac

# Use gcore on Solaris and Unixware
# 
# gcore appends ".<pid>" to the filename so, if the name does not end
# in ".<pid>", we need to use a temp name and rename it
case $COREFILE in
	*.$PID) exec gcore -o `echo "$COREFILE" | sed -e "s/\.$PID$//"` $PID
		exit 105
		;;

	*)	TMPFILE=/tmp/cobcr$$
		rm -f "$COREFILE" $TMPFILE.$PID || exit 106
		gcore -o $TMPFILE $PID || exit $?
		mv $TMPFILE.$PID "$COREFILE"
		if test $? -ne 0
		then
			rm -f $TMPFILE.$PID
			exit 106
		fi
		;;
esac

exit 0
