#! /bin/sh

orc=$?
set +e

# This script tries to grab a core file and analyze it, obtaining a
# backtrace.
# (C) 2003 Matthias Andree
#
# Redistributable in accordance with the terms and conditions of the
# GNU General Public License v2.
#
# THIS COMES WITHOUT ANY WARRANTIES!

: ${GDB=gdb}

# stage 1: find core file - we'll guess, not knowing all possible
#          core file name generators. Most tend to contain pid + "core"
#          or program name + "core".
corefile="$(find . -name '*core*' -print | grep -w core | head -n1)"
if [ -d "$TMPDIR" ] ; then
    corefile="$corefile$(find "$TMPDIR" -name '*core*' -print | grep -w core | head -n1)"
fi
if [ -z "$corefile" ] ; then
    if [ $orc -gt 0 ] ; then echo >&2 "No core file found" ; fi
    exit 0
fi
echo >&2 ">>> Using core file \"$corefile\"."
trap "rm -f \"$corefile\"" 0

# stage 2: pull name of executable file out of core
backtick='`'
LANG=C
LC_MESSAGES=C
export LANG LC_MESSAGES
rm -f exit.$$
execfile="`( $GDB -nw -batch -nx -silent -c "$corefile" < /dev/null)`"
if [ $? -gt 0 ]
then
    echo >&2 "Problem with GDB program \"$GDB\""
    exit 0
fi
execfile=`echo "$execfile" | grep -i 'ore was generated by' | cut -f2- -d$backtick | cut -f1 -d"'" | cut -f1 -d" "`
if [ -z "$execfile" ]
then
    echo >&2 "Cannot figure executable."
    exit 0
fi
echo >&2 ">>> Using exec file \"$execfile\"."

# stage 3: obtain backtrace
gdbfile="script.gdb.$$"
rm -f "$gdbfile"
cat <<_EOF > "$gdbfile"
set height 0
set width 0
echo <<< SIMPLE BACKTRACE <<<\n
backtrace
echo <<< FULL BACKTRACE <<<\n
backtrace full
quit
_EOF

cmd="gdb -nw -r -batch -nx -x "$gdbfile" -silent "$execfile" "$corefile" < /dev/null"
echo >&2 ">>> Running command: $cmd"
eval "$cmd"
rm -f "$gdbfile"
echo >&2 ">>> Done."
exit 0
