#!/bin/sh
# @@@ START COPYRIGHT @@@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# @@@ END COPYRIGHT @@@
#
#
if [ $# -lt 1 ]; then
	prog=monitor
elif [ "$1" = "--help" ]; then
	echo "$0 [<program>]"
	exit 0
else
	prog=$1
fi
echo "pstack-ing $prog"
w=`whoami`

MY_NODES_PRM=" -a "
if [ -n "$MY_NODES" ];then
    MY_NODES_PRM=$MY_NODES
fi

if [ -e $SQ_PDSH ]; then
	hosts=`$PDSH $MY_NODES_PRM $PDSH_SSH_CMD hostname|awk '{ print $2 }'|sort`
else
	hosts=`hostname`
fi
if [ "$prog" = "all" ]; then
	progall=1
	proglist=`pstat -l | sed 's|,| |g'`
else
	progall=0
	proglist=$prog
fi
for host in $hosts; do
	if [ -e $SQ_PDSH ]; then
		ssh="ssh -q $host"
	fi
	for prog in $proglist; do
		pids=`$ssh ps -ef|grep -v 'ps -ef'|grep -vw $0|grep -w $w|grep -w $prog|grep -vw mpirun|grep -vw grep|awk '{ print $2 }'`
		for pid in $pids; do
			if [ $progall = 1 ]; then
				echo "$ssh pstack $pid [$prog]"
			else
				echo $ssh pstack $pid
			fi
			$ssh pstack $pid
		done
		echo "--"
	done
done
