#! /bin/sh
#
# Author: Andrew Tridgell <tridge at samba dot org>

# we want everything on stderr, so the program is not disturbed
exec 1>&2

BASENAME=$(basename $0)

test -z ${GDB_BIN} && GDB_BIN=$(type -p gdb)
if [ -z ${GDB_BIN} ]; then
	echo "ERROR: ${BASENAME} needs an installed gdb. "
	exit 1
fi

if [ -z $1 ]; then
	echo "ERROR: ${BASENAME} needs a PID. "
	exit 1
fi
PID=$1

# use /dev/shm as default temp directory
test -d /dev/shm &&
	TMP_BASE_DIR=/dev/shm ||
	TMP_BASE_DIR=/var/tmp
TMPFILE=$(mktemp -p ${TMP_BASE_DIR} backtrace.XXXXXX)
if [ $? -ne 0 ]; then
	echo "ERROR: ${basename} can't create temp file in ${TMP_BASE_DIR}. "
	exit 1
fi

cat <<EOF >"${TMPFILE}"
set height 0
up 8
bt full
quit
EOF

${GDB_BIN} -x "${TMPFILE}" "/proc/${PID}/exe" "${PID}"

/bin/rm -f "${TMPFILE}"
