#!/bin/bash


# based on pstack. Automatically dumps the stack for all vertica
# processes for the current user

PIDS=`ps -eo pid,comm,euser | grep $USER |  awk '{ if ( \$2=="vertica" ) print \$1 " "}'`

echo "Attempting to dump pids: $PIDS for $USER"

GDB=${GDB:-/usr/bin/gdb}

if $GDB -nx --quiet --batch --readnever > /dev/null 2>&1; then
    readnever=--readnever
else
    readnever=
fi

for thepid in $PIDS; do

    echo "--------------------- CURRENT PID $thepid -----------------";

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

# GDB doesn't allow "thread apply all bt" when the process isn't
# threaded; need to peek at the process to determine if that or the
# simpler "bt" should be used.

    backtrace="bt"
    if test -d /proc/$thepid/task ; then
    # Newer kernel; has a task/ directory.
	if test `/bin/ls /proc/$thepid/task | /usr/bin/wc -l` -gt 1 2>/dev/null ; then
	    backtrace="thread apply all bt 100"
	fi
    elif test -f /proc/$thepid/maps ; then
    # Older kernel; go by it loading libpthread.
	if /bin/grep -e libpthread /proc/$thepid/maps > /dev/null 2>&1 ; then
	    backtrace="thread apply all bt 100"
	fi
    fi    
   
    # Run GDB, strip out unwanted noise.
    $GDB --quiet $readnever -nx /proc/$thepid/exe $thepid <<EOF 2>&1 | 
    $backtrace
EOF

    /bin/sed -n \
	-e 's/^(gdb) //' \
	-e '/^#/p' \
	-e '/^Thread/p'
done
