#!/bin/sh

if test $# -ne 1; then
    echo "Usage: `basename $0` <process-id>" 1>&2
    exit 1
fi

if test ! -r /proc/$1; then
    echo "Process $1 not found." 1>&2
    exit 1
fi

# Two alternatives as thread apply all doesn't work when no threads.
if test `ls /proc/$1/task | wc -l` -gt 1; then
    backtrace="thread apply all bt"
else
    backtrace="bt"
fi

# Run GDB, strip out unwanted noise.
gdb --quiet -nx /proc/$1/exe $1 <<EOF 2>&1 | 
$backtrace
EOF
sed \
    -e 's/^(gdb) //' \
    -e '/^[^#]/d'

