#!/bin/sh
# NOTE: External tools needed : procstat, awk, grep

# environment definitions
: ${GSTACK_PREFIX:=/usr/local}
: ${BSTACK_CMD:=${GSTACK_PREFIX}/share/bstack/gdb_bstack}
: ${GDB:=${GSTACK_PREFIX}/bin/gdb}

# Check the presence of the process id
if [ $# -ne 1 ]; then
    echo "Usage: $(basename) <process-id>" 1>&2
    exit 1
fi

# Check the BSTACK_CMD validity
if [ ! -r "${BSTACK_CMD}" ]; then
    # check a possible second option
    if [ -r ./gdb_bstack ]; then
	BSTACK_CMD="./gdb_bstack"
    else
	echo "gdb script ${BSTACK_CMD} missing" 1>&2
	exit 4
    fi
fi

# Check if the process id is valid
PID=$1
procstat $PID >/dev/null 2>/dev/null
if [ $? -ne 0 ]; then
    echo "$PID is not a valid process-id" 1>&2
    exit 2
fi

# retrieve the executable pathname
EXE=$(procstat -h -b $PID | awk '{ print $4 }')

# check the presence of gdb
if [ ! -x ${GDB} ]; then
    echo "gdb not found - has devel/gdb the GDB_LINK option enabled?" 1>&2
    exit 3
fi

# run gdb reducing the noise 
$GDB -nx --batch -x "${BSTACK_CMD}" "$EXE" $PID | grep -E '^#|^Thread'
