#!/bin/sh
# Return last modified core file in current working directory
# $Id$
doExtract=0
quiet=0
osName=`uname -s`

while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [--extract]\n" "${0}" >&2
		;;
	-extract | --extract)
		doExtract=1
		;;
	-q | -quiet | --quiet)
		quiet=1
		;;
	*)
		break
		;;
	esac
	shift
done

if test "${osName}" = "Darwin"
then # MacOS
	coreFiles=`ls -t /cores/core.* 2>/dev/null`
	for file in ${coreFiles}
	do
        	echo ${file}
        	exit 0
	done
fi

# try regular core.PID files first
coreFiles=`ls -t core.[0-9]* 2>/dev/null`
for file in ${coreFiles}
do
        echo ${file}
        exit 0
done
# try *.core.PID (e.g., from valgrind)
coreFiles=`ls -t *.core.[0-9]* *.core 2>/dev/null`
for file in ${coreFiles}
do
        echo ${file}
        exit 0
done

coreDumpControl=`which coredumpctl 2>/dev/null`
if test -n "${coreDumpControl}"
then
	# typical states for core file are none, missing, present
	lastAvailableCorePID=`${coreDumpControl} -q --no-pager -1 list $* | fgrep present | awk '{ print $5}'`
	if test -n "${lastAvailableCorePID}"
	then
		colorProg=`which colorText 2>/dev/null`
		if test -n "${colorProg}"
		then
			redColor="-red"
			greenColor="-green"
			blueColor="-blue"
			resetColor="-reset"
			foreground="-fg"
		else
			colorProg="echo"
		fi
		if test ${doExtract} -eq 0
		then # extraction not permitted
			if test ${quiet} -eq 0
			then # suggest usage of --extract
				${colorProg} "${0}:" ${redColor} no local core file, use ${greenColor} --extract ${redColor} option to retrieve core for PID ${blueColor} ${lastAvailableCorePID} ${redColor} using ${blueColor} coredumpctl ${resetColor} >&2
			fi
			exit 1
		fi
		coreFileName="core.${lastAvailableCorePID}"
		# we do not need the extra debug info
		${coreDumpControl} --no-pager -1 -o "${coreFileName}" dump ${lastAvailableCorePID} > /dev/null
		if test ! -s "${coreFileName}"
		then
			${colorProg} "${0}:" ${redColor} retrieval of ${blueColor} ${coreFileName} ${redColor} failed ${resetColor} >&2
			echo rm -f ${coreFileName}
			exit 1
		fi
		echo ${coreFileName}
		exit 0
	fi
fi
exit 1
