#!/bin/sh

# iscremotecc : wrapper to semplify the execution of iscremotecc service
# Copyright notice: Copyright (c) 2005 - 2025 Veryant
#
# Determine the version of ISCOBOL to use.
#
# If ISCOBOL has been set by the user, use that, otherwise, determine
# the location of this script (which is known to be $ISCOBOL/bin/iscremotecc)
# and derive the value of $ISCOBOL from that.
#

AddPath () {
  if [ -z "$2" ]; then
    echo $1
  else
    echo $1:$2
  fi
}

if [ -z "${ISCOBOL}" ]
then
    D=`dirname $0`
    B=`basename $0`
    abspath="`cd \"${D}\" 2>/dev/null && pwd || echo \"${D}\"`/${B}"
    _BIN_DIR=`dirname ${abspath}`
    ISCOBOL=`dirname ${_BIN_DIR}`
fi

if [ -f "$ISCOBOL/bin/default_java.conf" ]
then
. $ISCOBOL/bin/default_java.conf
fi


#
# Determine the version of the JDK to use.
#
# If the variable ISCOBOL_JDK_ROOT has been set, use that, otherwise
# derive the location of the JDK from the version of 'javac' that is
# on the user's path
#

if [ -z "${ISCOBOL_JDK_ROOT}" ]
then

    _JAVAC_LOCATION=`type javac | cut -f3 -d' '` 

    while [ -h "$_JAVAC_LOCATION" ]; do
       ls=`ls -ld "$_JAVAC_LOCATION"`
       link=`expr "$ls" : '.*-> \(.*\)$'`
       if expr "$link" : '/.*' > /dev/null; then
         _JAVAC_LOCATION="$link"
       else
         _JAVAC_LOCATION=`dirname "$_JAVAC_LOCATION"`/"$link"
       fi
    done  

    if [ -z "$_JAVAC_LOCATION" ]
    then
        echo "ERROR: Could not locate JDK. Please ensure that 'javac' is"
        echo "on your PATH or set ISCOBOL_JDK_ROOT"
        exit 1
    fi

    _JDK_BINDIR=`dirname $_JAVAC_LOCATION`
    ISCOBOL_JDK_ROOT=`dirname $_JDK_BINDIR`
fi

# Search for additional shared libraries.
if [ "`uname`" = "AIX" ]; then
  LIBPATH=`AddPath $ISCOBOL/native/lib $LIBPATH`
  export LIBPATH
elif [ "`uname`" = "HP-UX" ]; then
  SHLIB_PATH=`AddPath $ISCOBOL/native/lib $SHLIB_PATH`
  export SHLIB_PATH
else
  LD_LIBRARY_PATH=`AddPath $ISCOBOL/native/lib $LD_LIBRARY_PATH`
  export LD_LIBRARY_PATH
fi

#
# Now set classpath and invoke isCOBOL compiler
#

# Search for additional jar file libraries.

for f in $ISCOBOL/jars/*.jar
do
  if [ -z "${ISCOBOL_CLASSPATH}" ]
  then
    ISCOBOL_CLASSPATH=$f
  else
    ISCOBOL_CLASSPATH=$ISCOBOL_CLASSPATH:$f
  fi
done

for f in $ISCOBOL/lib/*.jar
do
  if [ -z "${ISCOBOL_CLASSPATH}" ]
  then
    ISCOBOL_CLASSPATH=$f
  else
    ISCOBOL_CLASSPATH=$ISCOBOL_CLASSPATH:$f
  fi
done

while [ $# -ne 0 ]
do
   case "$1" in 
       -J*) javaoptions="$javaoptions `echo $1 | cut -c3-`" ;;
         *) cobolarg="$cobolarg $1";;          
   esac
   shift
done

ISCOBOL_CLASSPATH=$ISCOBOL_CLASSPATH:$CLASSPATH

if [ -z "${_JDK_BINDIR}" ]
then
    $ISCOBOL_JDK_ROOT/bin/java -classpath $ISCOBOL_CLASSPATH $javaoptions com.iscobol.compiler.remote.server.Server $cobolarg 
else
    $_JDK_BINDIR/java -classpath $ISCOBOL_CLASSPATH $javaoptions com.iscobol.compiler.remote.server.Server $cobolarg 
fi
