#!/bin/bash -p
PROGNAME="${0##*/}"

# $Id: injar 3496 2020-09-07 14:28:12Z blaine $
#
# Copyright 2008 Axis Data Management Corp.
#
# Licensed 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.

set +u
shopt -s xpg_echo

RECURSIVE=
SYNTAX_MSG='SYNTAX:  injar [-vr] substring [directory|jar]'
[ $# -gt 0 ] && case "$1" in -*)
    case "$1" in *v*) VERBOSE=1;; esac
    case "$1" in *r*) RECURSIVE=1;; esac
    shift
esac
[ $# -lt 1 ] && {
    echo "\a$SYNTAX_MSG" 1>&2
    exit 2
}

[ -n "$TMPDIR" ] || TMPDIR=/tmp
TMPFILE="$TMPDIR/$PROGNAME.$$"
unset DIR JAR
STRING="$1"; shift
case $# in
    0);;
    1)
        if [ -d "$1" ]; then
            DIR="$1"
        else
            JAR="$1"
        fi
        shift
    ;;
    *)
        echo "\a$SYNTAX_MSG" 1>&2
        exit 2
    ;;
esac

[ -n "$JAR" ] && {
    jar -tf $JAR | grep -F "$STRING"
    exit 0
}
[ -n "$DIR" ] && {
    cd $DIR || exit 2
}

if [ -n "$RECURSIVE" ]; then
    find * -type f -name '*.jar'
else
    for file in *.jar; do [ -f "$file" ] && echo "$file"; done
fi > "$TMPFILE"
declare -a WCOUT=($(wc -l "$TMPFILE"))
echo "${WCOUT[0]} jars to search"
while read file; do
    echo -n .
    if [ -n "$VERBOSE" ]; then
    	jar -tf $file | grep -F "$STRING" && echo "  in $file\a"
    else
    	jar -tf $file | grep -F "$STRING" > /dev/null && echo "\n$file\a"
    fi
done < "$TMPFILE"
rm -f "$TMPFILE"
echo
