#!/bin/sh

className=$1
JAR=$JAVA_HOME/bin/jar
JARFILES=`find . -name "*jar"`
found=0
ask=1

#########################################
#Author: Rajdeep Biswas
#Created: 2014-04-30
#Website: www.javabambino.blogspot.com
#Known issue: Not for inner classes
#########################################
echo ""
echo "*****************************************"
echo "About: Searches .jar in current path (sub-directories inclusive) for a specified class file."
echo "Usage: $0 <class_name>"
echo "Example: $0 HashMap"
echo "Note: Give exact class name without .class extension."
echo "*****************************************"
echo ""

#Error if there is no or multiple arguments
if [ $# -ne 1 ]
then
	echo "ERROR: Wrong number of arguments specified, please check usage above!"
	exit 1;
fi

#Ask how to search
while [ $ask -eq 1 ]
do
	echo "1. Enter '1' to search for exactly $className.class"
	echo "2. Enter '2' to search for *$className.class pattern. For example, Sample$className.class"
	echo "3. Enter '0' to exit this program"
	read temp
	
#validate input is only 1, 2 or 0. If not, take input again.
	if [[ -n ${temp//[0-2]/} ]]; 
	then
		echo -e "Caution: Invalid input!\n"
		continue
	fi

	if [ $temp -eq 0 ]
	then
		echo "Exiting.."
		exit 1
	fi

	if [ $temp -eq 1 -o $temp -eq 2 ]
	then
		searchHow=$temp
		ask=0
	fi
done

#Set the grep pattern accordingly as user input on how to search
if [ $searchHow -eq 1 ]
then
	searchWhat="grep -w $className.class"
elif [ $searchHow -eq 2 ]
then
	searchWhat="grep $className.class"
fi

echo -e "Scanning started...\n"
#Start scan
for JARFILE in $JARFILES
do
	$JAR tvf $JARFILE | $searchWhat  > /dev/null
	
	if [ $? -eq 0 ]
	then
		found=1
		echo "==> Found in $JARFILE"
	fi
done
#End scan

if [ $found -eq 0 ]
then
	echo "$className.class not found in current path: "`pwd`
fi

echo -e "\nScanning over."
