#!/bin/bash
#
# Small script to build a classpath depending on the JVM used
#
# JPackage Project <http://www.jpackage.org/>
#

# Import java functions
[ -r "/opt/rh/eap8/root/usr/share/java-utils/java-functions" ] \
 &&  . "/opt/rh/eap8/root/usr/share/java-utils/java-functions" || exit 1

# Prints help message
usage() {
cat >&2 << EOF_USAGE
Usage: $0 [ -c <software_collection(s)> ] <jar1> [<jar2> .. <jarn>]
-c software_collection(s): name of software collections to get jar(s) from
      Example: eap8
jarX: name of a jar
      Example: jndi
EOF_USAGE
exit 2
}

[ "$#" -eq "0" ] && usage

set_javacmd || exit 3

check_java_env || exit 4

set_jvm_dirs || exit 5


build_classpath() {
    for extension in "$@" ; do
        unset _JARS
        extension=$(find_jar $extension)
        if [ "$?" -eq 0 ] ; then
            if [ -d "$extension" ] ; then
                 # Brute-force approach. If we can't specify a single jar, we can as
                # well take everything in the directory
                # This may create duplicates if symlinks point back inside the
                # directory structure, but who cares
                _JARS=$(find "$extension" -follow -name "*.jar" -xtype f -printf %p: 2>/dev/null)
            else
                _JARS=$extension:
            fi
            _CLASSPATH=$_CLASSPATH$_JARS
        else
            # Defer failure to get list of all errors in one shot
            _ALLFOUND="false"
        fi
    done
}

_ALLFOUND="true"
_CLASSPATH=

RPM_BIN=/bin/rpm
SCL_BIN=/usr/bin/scl

while getopts :c: opt; do
    case $opt in
        c)
            shift
            SCLS="$1"
            shift
            ;;
        \?)
            usage
            ;;
        :)
            usage
            ;;
    esac
done

if [ -z "$SCLS" ] && [ -n "$X_SCLS" ]; then
    SCLS="$X_SCLS"
fi

if [ -z "$SCLS" ] && [ -z "$X_SCLS" ] && [ -x $RPM_BIN ]; then
    SCL="`$RPM_BIN --eval '%scl'`"

   if [ "$SCL" != '%scl' ]; then
       SCLS="$SCL"
   fi
fi

if [ -n "$SCLS" ]  && [ -z "$X_SCLS" ]; then
    if [ -x "$SCL_BIN" ]; then
        $SCL_BIN enable $SCLS "$0 $*"
    else
        echo "$0: error: Software collections ["$SCLS"] specified, but "$SCL_BIN" not found" >&2
        exit 7
    fi
else
    build_classpath $*
fi

# Cleanup trailing :
_CLASSPATH="$(echo $_CLASSPATH | sed 's+:$++g')"

# Echo classpath whether it's complete or not
# Apps that do not care about a full classpath can redirect errors to /dev/null
if [ -n "$_CLASSPATH" ]; then
    echo "$_CLASSPATH"
fi

if [ "$_ALLFOUND" = "true" ] ; then
    exit 0
else
    echo "$0: error: Some specified jars were not found" >&2
    exit 6
fi
