#!/bin/bash
########################################################################
#  (@)sql.sh
#
#  Copyright 2014 by Oracle Corporation,
#  500 Oracle Parkway, Redwood Shores, California, 94065, U.S.A.
#  All rights reserved.
#
#  This software is the confidential and proprietary information
#  of Oracle Corporation.
#
# NAME	sql
#
# DESC 	This script starts SQL CL.
#
# AUTHOR bamcgill
#
# MODIFIED
#   bamcgill    21/03/2014  Created
#   bamcgill    18/07/2014  Simplified classpaths and args
#   bamcgill    11/12/2014  Renamed script and contents
#   bamcgill    16/01/2015  Renamed script and contents
#   bamcgill    05/02/2015  Added STD_ARGS for headless and other args
#   cdivilly    12/02/2015  Locate home folder via symlinks
#   bamcgill    10/06/2015  Quote jarfiles for dirs with spaces
#   bamcgill    02/10/2015  Adding specific JAVA_HOME for ADE dev users
#   totierne    02/10/2015  use -cp instead of JARFILE to add ojdbc6
#   bamcgill    14/10/2015  switch Cygwin settings so Cygwin Term will work
#   totierne    16/10/2015  add classpath to allow times ten jars
#   bamcgill    17/10/2015  Cleaning up bootstrap to call single java
#                           implementation with pruned args.
#   totierne    12/05/2016  added $OH/lib to $LD_LIBRARY_PATH when $OH
#   bamcgill    12/05/2016  adding -cleanup to args
#   bamcgill    29/06/2016  Added more checks around JAVA_HOME settings
#   bamcgill    04/07/2016  Using the ADE RDBMS JDK if it exists.
#   jmcginni    23/08/2016  Grab Proxy info on Mac, KDE, Gnome
#   bamcgill    04/11/2016  Added all jars to classpath and pointed cobertura
#                           ser file for running.
#   bamcgill    17/11/2016  Added $OH/jdk as java location if JAVA_HOME not set
#   bamcgill    16/10/2017  Enumerated the libraries for sqlcl to avoid unwanted
#                           class loads
#   bamcgill    11/03/2017  Added classpaths for jars in different locations
#                           embedded in Oracle SQLDeveloper
#   bamcgill    11/06/2017  Added classpaths for drivers and exts.
#   bamcgill    10/05/2019  Hardened support for MINGW console on windows
#   bamcgill    21/05/2019  Adding silence for nashorn warning after jdk11
#   bamcgill    19/06/2019  Adding slf4j as its used with lb support and
#                           the new ssh implementation:wq
#   bamcgill    14/11/2019  Removing funny comments from file.
#   skutz       29/01/2020  Added utility function to get java version and 
#                           used in in ADE setup function
#   bamcgill    12/03/2020  Adding LANG and LC_ALL variables for forcing 
#                           sqlcl into a particular language
#   bamcgill    03/06/2020  Changing the DEBUG Flag to be explicitly called 
#                           SQLCL_DEBUG which will allow debugging of sqlcl java.
#   bamcgill    23/07/2020  In docker alpine images, LANG defaults to C or posix
#                           in this case we default to en_US.UTF8
#   bamcgill    27/01/2021  Adding jars and flags for Graal.js support.  This is
#                           important as jdk15 removes nashorn which was deprecated
#                           in JDK11
#   bamcgill    28/03/2022  Adding Java Check for minimum of 11
#   josmende    01/11/2022  Adding eclipse parsson to the classpath
#   bamcgill    10/06/2023  Adding consolidated paths for sqldev next embedding.
#   jmcginni    09/08/2023  Add dbtools-utils jars to classpath
#   bamcgill    23/07/2023  Adding classpaths for cloud sdks
#   bamcgill    31/10/2023  Adding ORACLE_HOME Logic
#   bamcgill    06/03/2024  Add JDK11 check to bootstrap function
#   bamcgill    26/04/2024  Using $OH/bin/oraversion to determine DB SW version
#   dwhittin    04/10/2024  Removed osdt_cert and osdt_core jars from classpath
#########################################################################

USE_ORACLE_HOME=false
AddVMOption()
{
  APP_VM_OPTS[${#APP_VM_OPTS[*]}]="$*"
}

#function to allow users to see how the tool is choosing options
#Use environment variable DEBUG to start
function debug {
 if  [  "m$DEBUG" != "m" ];
then
  echo "DEBUG: line $1 : $2"
fi
}

function addLibraryPath {
    if [ `uname` = Darwin ] ; then
      export DYLD_LIBRARY_PATH="$1:$DYLD_LIBRARY_PATH"
    else
      export LD_LIBRARY_PATH="$1:$LD_LIBRARY_PATH"
    fi
}

# Utility function to get java version
function jdk_version() {
  local result
  local java_cmd
  if [[ (-n "$JAVA_HOME") && (-x "$JAVA_HOME/bin/java") ]]
    then
      java_cmd="$JAVA_HOME/bin/java"
  elif [[ -n $(type -p java) ]]
  then
    java_cmd=java
  fi
  local IFS=$'\n'
  # remove \r for Cygwin
  local lines=$("$java_cmd" -Xms32M -Xmx32M -version 2>&1 | tr '\r' '\n')
  if [[ -z $java_cmd ]]
  then
    result=no_java
  else
    for line in $lines; do
      if [[ (-z $result) && ($line = *"version \""*) ]]
      then
        local ver=$(echo $line | sed -e 's/.*version "\(.*\)"\(.*\)/\1/; 1q')
        # on macOS, sed does not support '?'
        if [[ $ver = "1."* ]]
        then
          result=$(echo $ver | sed -e 's/1\.\([0-9]*\)\(.*\)/\1/; 1q')
        else
          result=$(echo $ver | sed -e 's/\([0-9]*\)\(.*\)/\1/; 1q')
        fi
      fi
    done
  fi
  echo "$result"
}

#
# Check ORACLE_HOME against supported versions
#
function checkOracleHome {

# Using the product version here so we can identify and compare $ORACLE_HOME support
local PRODUCT_VERSION=24.3.1
local BASEVERSION=`echo $PRODUCT_VERSION|awk -F. {'print $1'}`
DBVERSION=21
if [[ -n "$ORACLE_HOME" ]];
then
  debug $LINENO "ORACLE_HOME found at $ORACLE_HOME"
  if [[ -f $ORACLE_HOME/bin/oraversion ]];
  then
  DBVERSION=`$ORACLE_HOME/bin/oraversion -majorVersion`    
  fi
  #ORACLE_HOME 23 AND ORACLE_HOME 21 work. May have to remove 21 when we
  #  compile with 23 jdbc driver.
  if test "$DBVERSION" -lt "$BASEVERSION" -a "$DBVERSION" -ne "21" -a "$DBVERSION" -ne "23"
  then
    debug $LINENO "ORACLE_HOME version $DBVERSION is lower than SQLCL driver version 21"
    echo
    echo "Warning: ORACLE_HOME must be database version 21 or later"
    echo "         Thick driver unavailable for use."
    echo
    AddVMOption -Doracle.sqlcl.skipOracleHome=true
  else
    USE_ORACLE_HOME=true
  fi

else
  USE_ORACLE_HOME=false
  debug $LINENO "Not using Oracle Home"
fi
}

#
# set up the main arguments for java.
#
function setupArgs {
	#
	# Standard JVM options which are always used
	#
  AddVMOption -Dpolyglot.engine.WarnInterpreterOnly=false
	AddVMOption -Djava.awt.headless=true
	if [[ $JAVA_INUSE -eq 11 ]] || [[ $JAVA_INUSE -gt 11 ]];
	then	
          AddVMOption -Dnashorn.args="--no-deprecation-warning"
	fi
	AddVMOption -Dapple.awt.UIElement=true
	AddVMOption -Xms64M
	AddVMOption -Xmx2G
  AddVMOption -Xss100m
	if test "m$(uname -s)" = "mHP-UX"
	then
	   AddVMOption -d64
	fi
	# ignore cover up windows registry warning which errors on java 8
	AddVMOption -XX:+IgnoreUnrecognizedVMOptions
	# cover up windows read registry warning and reflective access by JLine to private static class of ProcessBuilder
        AddVMOption --add-opens=java.prefs/java.util.prefs=ALL-UNNAMED
        AddVMOption --add-opens=java.base/java.lang=ALL-UNNAMED
  # enable graal scripts
  AddVMOption -Dpolyglot.js.nashorn-compat=true
}

#
# Set SQLHOME to be canonical paths
#
function setupSQLHome {
	#
	# resolve the folder where this script is located, traversing any symlinks
	#
	PRG="$0"
	# loop while $PRG is a symlink
	while [ -h "$PRG" ] ; do
	  # figure out target of the symlink
	  ls=`ls -ld "$PRG"`
	  link=`expr "$ls" : '.*-> \(.*\)$'`
	  # traverse to the target of the symlink
	  if expr "$link" : '/.*' > /dev/null; then
	  PRG="$link"
	  else
	  PRG=`dirname "$PRG"`"/$link"
	  fi
	done

	#
	# SQLHOME is where we live.  Lets get an exact address.
	# sql script is in ${SQL_HOME}/bin so lets check above and get the
	# canonical path for that
	#
	SQL_HOME=`dirname "$PRG"`/..
	export SQL_HOME=`cd "${SQL_HOME}" > /dev/null && pwd`
}

function setupCPLIST {
CPLIST="$SQL_HOME/../../jlib/orai18n.jar"
CPLIST="$SQL_HOME/../../jlib/orai18n-mapping.jar:$CPLIST"
CPLIST="$SQL_HOME/../../jlib/orai18n-utility.jar:$CPLIST"
CPLIST="$SQL_HOME/../jlib/orai18n.jar:$CPLIST"
CPLIST="$SQL_HOME/../jlib/orai18n-mapping.jar:$CPLIST"
CPLIST="$SQL_HOME/../jlib/orai18n-utility.jar:$CPLIST"
CPLIST="$SQL_HOME/../../rdbms/jlib/xdb6.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-sqlcl.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-common.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-data.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-http.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-net.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/antlr-runtime.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/antlr4-runtime.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jline.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jansi.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/orai18n-mapping.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jdbcrest.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/commons-codec.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/sshd-osgi.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/sshd-contrib.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/sshd-putty.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/eddsa.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/orai18n-servlet.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-core.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-oci.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/guava.jar:$CPLIST"

CPLIST="$SQL_HOME/lib/dbtools-arbori.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-data.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-datapump.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-cpat.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-common.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-http.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-net.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/sqlcl-jline.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-sqlcl.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-sqlcl-console.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/dbtools-datapump.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/ojdbc11.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/ucp11.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/nucleo-jdbc.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/nucleo-driver.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/ipclnt.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/orai18n-utility.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/httpclient5.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/orajsoda.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/httpcore5.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/httpcore5-h2.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jackson-annotations.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oraclepki.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/ST4.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jackson-core.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/xdb6.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/xdb.jar:$CPLIST"
CPLIST="$SQL_HOME/../rdbms/jlib/xdb6.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jackson-jr-objects.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jackson-jr-stree.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/orai18n-collation.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/xmlparserv2-sans-jaxp-services.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/orai18n.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/commons-logging.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/xmlparserv2.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jakarta.json-api.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/parsson.jar:$CPLIST"

#OCI SDK
CPLIST="$SQL_HOME/lib/oci-java-sdk-bastion.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-circuitbreaker.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-common-httpclient-jersey3.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-common-httpclient.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-common.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-database.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-databasetools.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-identity.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-secrets.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-secrets.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-workrequests.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jakarta.ws.rs-api.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jakarta.annotation-api.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jersey-common.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jakarta.inject-api.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/osgi-resource-locator.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jersey-client.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jersey-media-json-jackson.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jersey-entity-filtering.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jackson-module-jakarta-xmlbind-annotations.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jakarta.activation.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jakarta.xml.bind-api.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jersey-hk2.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/hk2-api.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/hk2-locator.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/hk2-utils.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/httpcore.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/httpclient.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/aopalliance-repackaged.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/javassist.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jersey-apache-connector.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/resilience4j-circuitbreaker.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/resilience4j-core.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/vavr-match.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/vavr.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/eddsa.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jackson-databind.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jackson-datatype-jsr310.jar:$CPLIST"
#Bouncycastle libraries (for OCI SDK)
CPLIST="$SQL_HOME/lib/bcpkix-jdk15to18.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/bcutil-jdk15to18.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/bcprov-jdk15to18.jar:$CPLIST"


CPLIST="$SQL_HOME/lib/slf4j-jdk14.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/slf4j-api.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/jcl-over-slf4j.jar:$CPLIST"


CPLIST="$SQL_HOME/lib/sshd-scp.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/sshd-sftp.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/assertj-core.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/byte-buddy.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/low-level-api.jar:$CPLIST"

#SQLDeveloper file locations (when embedded)
CPLIST="$SQL_HOME/../modules/oracle.xdk/xmlparserv2.jar:$CPLIST"
CPLIST="$SQL_HOME/../jlib/orai18n.jar:$CPLIST"
CPLIST="$SQL_HOME/../jlib/orai18n-mapping.jar:$CPLIST"
CPLIST="$SQL_HOME/../jlib/orai18n-utility.jar:$CPLIST"
CPLIST="$SQL_HOME/../jdbc/lib/ojdbc11.jar:$CPLIST"
CPLIST="$SQL_HOME/../rdbms/jlib/xdb6.jar:$CPLIST"
CPLIST="$SQL_HOME/../rdbms/jlib/xdb.jar:$CPLIST"

CPLIST="$SQL_HOME/lib/ext/*:$CPLIST"
CPLIST="$SQL_HOME/lib/xmlparserv2_sans_jaxp_services.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/slf4j-api.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/slf4j-jdk14.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/drivers/*:$CPLIST"

# Adding classpaths for Cloud vendor Java SDKs
CPLIST="$SQL_HOME/lib/sdks/oci/*:$CPLIST"
CPLIST="$SQL_HOME/lib/sdks/aws/*:$CPLIST"
CPLIST="$SQL_HOME/lib/sdks/google/*:$CPLIST"
CPLIST="$SQL_HOME/lib/sdks/azure/*:$CPLIST"
CPLIST="$SQL_HOME/lib/sdks/graaljs/*:$CPLIST"

#SQLDEV Next Jars
CPLIST="$SQL_HOME/../lib/modules/ST4.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/modules/antlr-runtime.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/modules/dbtools-common.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/modules/guava.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/classpath/jackson-core.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/classpath/jackson-jr-objects.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/classpath/jackson-jr-stree.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/modules/jakarta.json-api.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/modules/ojdbc11.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/modules/oraclepki.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/modules/orajsoda.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/modules/parsson.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/modules/xdb.jar:$CPLIST"
CPLIST="$SQL_HOME/../lib/modules/xmlparserv2_sans_jaxp_services.jar:$CPLIST"

# OCI Libraries 
CPLIST="$SQL_HOME/lib/oci-java-sdk-bastion.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-common.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-databasetools.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-objectstorage-generated.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-common-httpclient.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-database.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-identity.jar:$CPLIST"
CPLIST="$SQL_HOME/lib/oci-java-sdk-secrets.jar:$CPLIST"

if [ ! -z ${GRAALVM} ] &&  [ -d $GRAALVM ];
then
  CPLIST="$GRAALVM/jre/languages/js/graaljs.jar:$CPLIST"
  CPLIST="$GRAALVM/jre/tools/regex/tregex.jar:$CPLIST"
  CPLIST="$GRAALVM/jre/lib/boot/graal-sdk.jar:$CPLIST"
  CPLIST="$GRAALVM/jre/lib/truffle/truffle-api.jar:$CPLIST"
  CPLIST="${GRAALVM}/jre/lib/boot/graaljs-scriptengine.jar:${CPLIST}"
  CPLIST="${GRAALVM}/jre/languages/js/icu4j.jar:${CPLIST}"
fi

}

#
# Setup classpath depending on where we are
#
function setupClasspath {
    # Bootstrap classpath
    setupCPLIST
	#
	# This $USE_ORACLE_HOME comes from function setupOracleHome
	if [[ "${USE_ORACLE_HOME}" = "true" ]];
	then
	  #
	  # If we are in an ORACLE_HOME, then we want to try to use the jdbc
	  # drivers in there.
	  # Here we are frontloading the Oracle JDBC jars. We are not version
	  # checking at this stage.
  	  #
	  if test  "m$ORACLE_HOME" = "m"
	  then
	     CPLIST="$SQL_HOME/lib/dbtools-sqlcl.jar:$CPLIST:$CLASSPATH"
	  else
	     # where ORACLE_HOME points to ordinary ORACLE_HOME or
	     # INSTANT_CLIENT (or use shipped with sqlcl ojdbc8.jar)
	     CPLIST="$ORACLE_HOME/jdbc/lib/ojdbc11.jar:$ORACLE_HOME/jdbc/lib/ojdbc8.jar:$ORACLE_HOME/ojdbc11.jar:$ORACLE_HOME/ojdbc8.jar:$ORACLE_HOME/jdbc/lib/ojdbc7.jar:$ORACLE_HOME/ojdbc7.jar:$ORACLE_HOME/jdbc/lib/ojdbc6.jar:$ORACLE_HOME/ojdbc6.jar:$CPLIST:$CLASSPATH"
	     addLibraryPath "$ORACLE_HOME/lib:$ORACLE_HOME"
	  fi
  fi
	if test "m$(uname -s)" = "mAIX"
	then
	   export LIBPATH=$LD_LIBRARY_PATH:$LIBPATH
	fi

	#
	# Lets look for jars in the extensions
	# directory under lib.  These will be loaded
	# at startup as well.
	#
	if  [ -f "$SQL_HOME/cobertura.ser" ]
	then
	#Setup cobertura classpath
		COBERTURA="$SQL_HOME/lib/cobertura-2.1.1.jar"
		INSTRUMENTED_CLASSES="$SQL_HOME/lib/dbtools-common.jar:$SQL_HOME/lib/dbtools-sqlcl.jar"
		CPLIST="$COBERTURA:$INSTRUMENTED_CLASSES:$SQL_HOME/lib/*:$CLASSPATH"
		AddVMOption -Dnet.sourceforge.cobertura.datafile="$SQL_HOME/cobertura.ser"
	fi
}
#
# Do you use cygwin?  Lets see and make the classpath right
#
function checkCygwin {

#
# Ok, now we have a classpath, lets make sure it works with Cygwin too.
#
	#
	# Check for Cygwin
	#
	cygwin=false
	case `uname` in
		MINGW64*) cygwin=true;;
		 CYGWIN*) cygwin=true;;
	esac

	#
	# If its Cygwin, then convert the classpath to posix style.
	# Convert the terminal to something that the Cygwin terminal
	# will understand and force jline to use a unix terminal as
	# cygwin reports TTY style badly
	if $cygwin; then
	 CPLIST=$(cygpath -pw "$CPLIST")
	 stty -icanon min 1 -echo > /dev/null 2>&1
	 stty icanon echo > /dev/null 2>&1
	 CYGWIN=-Djline.terminal=jline.UnixTerminal
	fi
}

#
# Check if JAVA_HOME is set and if so, make sure we run the java there.
#
function checkJavaLocation {

#Test for JAVA_HOME settings.  If it is set, we want to use it over and above what /usr/bin/java says
JAVA=java
local JAVA_CONFIG=NOTFOUND
# Rules for finding Java
# 1. If JDK/JRE exists at sqlcl folder level, that is picked by Sqlcl.
# 2. Then, it checks for JAVA_HOME environment variable.
# 3. If JAVA_HOME not set, then it looks for Java version from the current ORACLE_HOME.
# 4. If SQLcl is installed as part of SQLDeveloper, it will look in the sqldeveloper home directory
# 5. If ORACLE_HOME is not set, then it uses the Java version appearing first in PATH.

  # 1. If JDK/JRE exists at sqlcl folder level, that is picked by Sqlcl.
  # If you have downloaded a jre, dropping it into sqlcl as jre will make it first in line
  if [ "${JAVA_CONFIG}" != "FOUND" ] && [ -d "$SQL_HOME/jre/" ]; then
	  JAVA_HOME="$SQL_HOME/jre/"
	  PATH="$JAVA_HOME/bin:$PATH"
    JAVA="$JAVA_HOME/bin/java"
    debug  $LINENO "Java found in  \$SQL_HOME/jre"
    JAVA_CONFIG="FOUND"
  fi

  # 2. Then, it checks for JAVA_HOME environment variable.
  if  [ "${JAVA_CONFIG}" != "FOUND" ] && [  "m$JAVA_HOME" != "m" ]; then
    if  [ -d "$JAVA_HOME" ];
    then
      debug $LINENO "JAVA_HOME set to $JAVA_HOME"
 	    JAVA="$JAVA_HOME/bin/java";
 	    JAVA_CONFIG="FOUND"
 	    debug $LINENO "Java found in JAVA_HOME"
    fi
  fi

  # 3. If JAVA_HOME not set, then it looks for Java version from the current ORACLE_HOME.
  if [ "${JAVA_CONFIG}" != "FOUND" ] && [  "m$ORACLE_HOME" != "m" ]; then
    debug $LINENO "Checking for ORACLE_HOME jdk"
    #if there is a jdk in the Oracle home and JAVA_HOME is not set
     if  [ -d "$ORACLE_HOME/jdk" ] && [  "m$JAVA_HOME" == "m" ];
     then
       debug  $LINENO "jdk found in \$ORACLE_HOME ${ORACLE_HOME}"
       JAVA_HOME="$ORACLE_HOME/jdk";
       JAVA="$JAVA_HOME/bin/java"
       JAVA_CONFIG="FOUND"
       debug $LINENO "Java found in ORACLE_HOME"
     fi
   fi

  # 4. If SQLcl is installed as part of SQLDeveloper, it will look in the sqldeveloper home directory
  # If you have downloaded sqldeveloper, with sqlcl in it, embedded jre will be here
    if  [ "${JAVA_CONFIG}" != "FOUND" ] && [ -d "$SQL_HOME/../jdk/jre/" ]; then
      debug $LINENO "Checking for jdk in sqldeveloper"
	    JAVA_HOME="$SQL_HOME/../jdk/jre/"
	    PATH="$JAVA_HOME/bin:$PATH"
      JAVA="$JAVA_HOME/bin/java"
      debug $LINENO "Java found in sqldeveloper install"
  fi

  debug $LINENO "JAVA_HOME=$JAVA_HOME"
  debug $LINENO "PATH=$PATH"
  debug $LINENO "Java=$JAVA"
  debug $LINENO "Which Java=`command -v java`"
  JAVA_INUSE=`$JAVA -version  2>&1 >/dev/null | grep  version| awk -F\" {'print $2'} | awk -F. {'print $1'}`
  debug $LINENO $JAVA_INUSE
}
#
# Check for proxies
#

# The following HTTP proxy-related code taken from NetBeans nbexec script.
DetectSystemHttpProxySetting()
{

    unset http_proxy_tmp

    if [ `uname` = Darwin ] ; then
	detect_macosx_proxy
    else
	if [ "$KDE_FULL_SESSION" = "true" ] ; then
            detect_kde_proxy
	else
            if [ ! -z "$GNOME_DESKTOP_SESSION_ID" ] ; then
        	detect_gnome_proxy
            fi
	fi
    fi

    # fall back to the environment-defined http_proxy if nothing found so far
    if [ -z "$http_proxy_tmp" ]; then
	http_proxy_tmp=$http_proxy
    fi

    if [ ! -z "$http_proxy_tmp" ] ; then
	    AddVMOption -Ddbtools.system_http_proxy=$http_proxy_tmp
	    AddVMOption -Ddbtools.system_http_non_proxy_hosts=$http_non_proxy_hosts
    fi

    if [ ! -z "$socks_proxy_tmp" ] ; then
	    AddVMOption -Ddbtools.system_socks_proxy=$socks_proxy_tmp
	    AddVMOption -Doracle.jdbc.javaNetNio=false
    fi

}

#
# figure out why locale settings are done in the terminal.
# we're supporting these formats
#    en
#    en_US
#    en_US.UTF-8
#    en_US.UTF-8@modifier
#    en.UTF-8
#    en.UTF-8@modifier
#    en@modifier
#    en_US@modifier
# 
function checkLanguageSettings () {
# Use LC_MESSAGE if set; otherwise, use LANG
  local TMPLANG=${LC_MESSAGE:-${LANG}}
  # echo ${TMPLANG}
    if [ ! -z "${TMPLANG}" ] ; then
        local IFS=@
        set -- $TMPLANG
        if [ ! -z  $2 ]; then
         local SQLCL_MODIFIER=$2
        fi
        local IFS=.
        set -- $1
        if [ ! -z $2 ]; then
         local SQLCL_ENCODING=$2
        fi
        local IFS=_
        set -- $1
        if [ ! -z $2 ]; then
         local SQLCL_TERRITORY=$2
        fi
        local SQLCL_LANG=$1
        if [ "${SQLCL_LANG}" = "C" -o "${SQLCL_LANG}" = "POSIX" ]
        then 
           # for straight C/POSIX, drop in ascii with us english
            SQLCL_LANG="en"
            SQLCL_TERRITORY="US"
           if [ ! -z ${SQLCL_ENCODING} ]
           then
             SQLCL_ENCODING=UTF8
           fi
        fi
        if [ ! -z "${SQLCL_LANG}" ] ; then
           AddVMOption -Duser.language=${SQLCL_LANG}
        fi

        if [ ! -z "${SQLCL_TERRITORY}" ] ; then
          AddVMOption -Duser.region=${SQLCL_TERRITORY}
        fi

        if [ ! -z "${SQLCL_ENCODING}" ] ; then
           AddVMOption -Dfile.encoding=${SQLCL_ENCODING}
        fi
   fi
}

detect_system_proxy () {
    if [ ! -z "$http_proxy" ]; then
        http_proxy_tmp=$http_proxy
    fi
    return 0
}

detect_gnome_proxy () {
    gconftool=/usr/bin/gconftool-2
    if [ -x  $gconftool ] ; then
        proxy_mode=`$gconftool --get /system/proxy/mode 2>/dev/null`
        if [ "$proxy_mode" = "manual" ] ; then
            http_proxy_host=`$gconftool --get /system/http_proxy/host 2>/dev/null`
            http_proxy_port=`$gconftool --get /system/http_proxy/port 2>/dev/null`
            http_proxy_tmp=$http_proxy_host:$http_proxy_port
            http_non_proxy_hosts=`$gconftool --get /system/http_proxy/ignore_hosts 2>/dev/null`
            if [ $? ] ; then
                http_non_proxy_hosts=`echo $http_non_proxy_hosts | /bin/sed 's/\]//'`
            fi
            socks_proxy_host=`$gconftool --get /system/proxy/socks_host 2>/dev/null`
            socks_proxy_port=`$gconftool --get /system/proxy/socks_port 2>/dev/null`
            socks_proxy_tmp=$socks_proxy_host:$socks_proxy_port

            return 0
        else
            if [ "$proxy_mode" = "none" ] ; then
                detect_system_proxy
                if [ -z "$http_proxy_tmp" ]; then
                    http_proxy_tmp="DIRECT"
                fi
                return 0
            else
                if [ "$proxy_mode" = "auto" ] ; then
                    detect_system_proxy
                    pac_file=`$gconftool --get /system/proxy/autoconfig_url 2>/dev/null`
                    if [ ! -z "$pac_file" ]; then
                        http_proxy_tmp="PAC "$pac_file
                    fi
                    return 0
                fi
            fi
        fi
    fi
    return 1
}

detect_kde_proxy () {
    kioslaverc="${HOME}/.kde/share/config/kioslaverc"
    if [ -f $kioslaverc ] ; then
        if /bin/grep 'ProxyType=1' "$kioslaverc" >/dev/null 2>&1; then
            http_proxy_tmp=`/bin/grep 'httpProxy=http://' "$kioslaverc"`
            if [ $? ] ; then
                http_proxy_tmp=`echo $http_proxy_tmp | /bin/sed 's/httpProxy=http:\/\///'`
                return 0
            fi
            http_non_proxy_hosts=`/bin/grep 'NoProxyFor=' "$kioslaverc"`
            if [ $? ] ; then
                http_non_proxy_hosts=`echo $http_non_proxy_hosts | /bin/sed 's/NoProxyFor=//'`
            fi
        else
            if /bin/grep 'ProxyType=0' "$kioslaverc" >/dev/null 2>&1; then
                detect_system_proxy
                if [ -z "$http_proxy_tmp" ]; then
                    http_proxy_tmp="DIRECT"
                fi
                return 0
            else
                if /bin/grep 'ProxyType=2' "$kioslaverc" >/dev/null 2>&1; then
                    pac_file=`grep "Proxy Config Script=" $kioslaverc  | cut -f 2 -d =`
                    http_proxy_tmp="PAC "$pac_file
                    return 0
                fi
            fi
        fi
    fi
    return 1
}

detect_macosx_proxy () {
    if [ ! -x /usr/sbin/scutil ] ; then
	return 1
    fi

    scutil_out=/tmp/nb-proxy-detection.$$
    cat <<EOF | /usr/sbin/scutil > ${scutil_out}
open
show State:/Network/Global/Proxies
close
EOF

    if /usr/bin/grep "ProxyAuto.*: *1" ${scutil_out} >/dev/null 2>&1; then
        if  /usr/bin/grep "ProxyAutoConfigEnable.*: *1" ${scutil_out} >/dev/null 2>&1; then
            http_proxy_tmp="PAC `/usr/bin/grep ProxyAutoConfigURLString ${scutil_out} | /usr/bin/awk 'END{print $3}'`"
            rm ${scutil_out}
            return 0
        fi

        rm ${scutil_out}
        return 1
    fi

    if /usr/bin/grep "HTTPEnable *: *1" ${scutil_out} >/dev/null 2>&1; then
	http_proxy_host=`/usr/bin/grep HTTPProxy ${scutil_out} | /usr/bin/awk 'END{print $3}'`
	http_proxy_port=`/usr/bin/grep HTTPPort ${scutil_out} | /usr/bin/awk 'END{print $3} '`
        http_proxy_tmp=$http_proxy_host:$http_proxy_port
        rm ${scutil_out}
        return 0
    fi

    http_proxy_tmp="DIRECT"
    rm ${scutil_out}
    return 0
}

#
# if we have a debug flag, we want to remove it, but also tell java
# to switch on debugging. Hence we'll need a new array to pass to java
#
function processArgs {
 id=0;
 ISDEBUG=0;
 for var
 do
    if [ $var != '-debug' ]
    then
      ARGS[id]=$var;
      let id++;
    else
      ISDEBUG=1;
    fi
 done
 if [ $ISDEBUG == 1 ]
 then
    SQLCL_DEBUG="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=8000"
 else
    SQLCL_DEBUG=""
 fi
}

#
# Run the tool.
#
function run {
 if  [  "m$SQLCL_DEBUG" != "m" ]; then
   echo "JAVA=$JAVA"
   echo "JAVA_OPTS=${APP_VM_OPTS[@]}"
   echo "DEBUG=$DEBUG"
   echo "CPLIST=$CPLIST"
    if [ `uname` = Darwin ] ; then
      echo "DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH"
    else
      echo "LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
    fi
   echo "$JAVA  $CUSTOM_JDBC $CYGWIN "${APP_VM_OPTS[@]}" -client $SQLCL_DEBUG -cp "$CPLIST" oracle.dbtools.raptor.scriptrunner.cmdline.SqlCli "

 fi
"${JAVA}"  ${CUSTOM_JDBC} ${CYGWIN} "${APP_VM_OPTS[@]}" -client ${SQLCL_DEBUG} -cp "$CPLIST" oracle.dbtools.raptor.scriptrunner.cmdline.SqlCli "$@"
}

#
# This is where we start SQLcl properly. We are going to process the arguments
# sent in, build our classpath, build our JVM options, prepare the terminal
# and kick off the main.
#
function bootStrap {
	echo "$@" | grep '\-debug' > /dev/null 2>&1
	if test "m$?" != "m0"
	then
		#if it is not debug we can pass the arguments straight through
		#runNormalArgs
 		run "$@"
	   exit $?
	else
		# Process the arguments and see if we have are in debug mode
		processArgs "$@"
		#
		# if you want to see what is getting passed, uncomment the next line
		#echo "after process args ${ARGS[@]}"
		#runModifiedArgs
		run ${ARGS[*]}
	fi
}



checkOracleHome
setupSQLHome
setupClasspath
checkCygwin
checkJavaLocation
checkLanguageSettings
setupArgs
DetectSystemHttpProxySetting
if [[ "$(jdk_version)" -ge "11" ]]; then
  bootStrap "$@"
else
  echo
  echo "Error: SQLcl requires Java 11 and above to run."
  echo "       Found Java version $(jdk_version)."
  echo "       Please set JAVA_HOME to appropriate version."
  echo
  exit 1
fi
