#!/bin/sh

#############################################################################
#
# Copyright (c) 2009-2012, EBM WebSourcing
# 
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA 
#
#############################################################################
#
#                      Petals ESB - JVisualVM Script
#
#  Description: This script launchs an instance of JVisualVM connected to a
#	local instance of Petals ESB
#
# Environment variables:
#	JAVA_HOME	Directory containing the JRE. Use the java executable
#			found in $PATH if not defined.
#
#############################################################################

# Set the path to the JVisualVM executable
JVISUALVM="$JAVA_HOME/bin/jvisualvm"
[ -x "$JVISUALVM" ] || JVISUALVM="`which jvisualvm`" || {
	echo "ERROR: JVisualVM executable not found" >&2
	exit 1
}

# Adapt pathes if architecture is Cygwin
case "`uname`" in
	CYGWIN*)
		JVISUALVM="`cygpath --unix "$JVISUALVM"`"
		;;
esac

PETALS_PIDS=`ps -e -o pid -o args | grep petals-launcher | grep -v grep | cut -d" " -f1`

if [ $# -eq 0 ]; then
	# No PID is set as argument, we check that only one Petals ESB process is running before to connect to it
	PETALS_PIDS_NB=`echo $PETALS_PIDS | wc -w`
	if [ $PETALS_PIDS_NB -gt 1 ]; then
		echo "Several Petals ESB processes are running locally. Please choose one:"
		for PID in $PETALS_PIDS;
		do
			echo "\t- $PID";
		done
		exit 1;
	else
		PETALS_PID=`echo $PETALS_PIDS`
	fi
else
	PETALS_PID=$1
fi

# A PID is set, we check that it is a Petals ESB process
CHECKED_PETALS_PID=`ps -o pid -o args $PETALS_PID | grep petals-launcher`
if [ "$CHECKED_PETALS_PID" != "" ]; then
	# The PID is a Petals ESB process, we connect to it
	echo "Launching an instance of JVisualVM connected to the Petals ESB process (pid = $PETALS_PID)."
	"$JVISUALVM" --openpid $PETALS_PID &
else
	# The PID is not a Petals ESB process
	echo "The process (pid=$PETALS_PID) does not exist or is not a Petals ESB process. Available processe(s) is(are):"
	for PID in $PETALS_PIDS;
	do
		echo "\t- $PID";
	done
	exit 1
fi
