# if this file is executed, /bin/sh is used, as we don't start with #!
# this should work under ash, bash, zsh, ksh, sh style shells.

#the purpose of this file is to check/set up the environment for greenstone3
#sorts out:
#  - gsdl3home
#  - java

# java_min_version gets passed to search4j as the minimum java version
java_min_version=1.11.0
DEBUG=false
# set the following if you want to use your system Perl (use an appropriate location)
#GSPERL_WITH_CPAN_HOME=/usr

testSource() {

  if test "$0" != "`echo $0 | sed s/gs3-setup\.sh//`" ; then
  # if $0 contains "gs3-setup.sh" we've been run... $0 is shellname if sourced.
  # One exception is zsh has an option to set it temporarily to the script name
    if test -z "$ZSH_NAME" ; then
    # we aren't using zsh
     gsdl_not_sourced=true
   fi 
  fi

  if test -n "$gsdl_not_sourced" ; then
     echo "  Error: Make sure you source this script, not execute it. Eg:"
     echo "    $ . ./gs3-setup.sh"
     echo "  or"
     echo "    $ source ./gs3-setup.sh"
     echo "  not"
     echo "    $ ./gs3-setup.sh"
     unset gsdl_not_sourced
     exit 1
  fi

  if test ! -f gs3-setup.sh ; then
    echo "You must source the script from within the Greenstone home directory"
    return 1
  fi
  return 0
}

# if GSDL3SRCHOME is set, then we assume that we have already sourced the 
# script so don't do it again. UNLESS, GSDL3SRCHOME doesn't match the 
# current directory in which case it was a different gs3 installation, so lets
# do it now.
testAlreadySourced() {
  if [ ! -z "$GSDL3SRCHOME" ] ; then 
    localgs3sourcehome="`pwd`"
    if [ "$GSDL3SRCHOME" = "$localgs3sourcehome" ] ; then
      echo "Your environment is already set up for Greenstone3"
      return 1
    fi
    echo "Your environment was set up for Greenstone 3 in $GSDL3SRCHOME."
    echo "Overwriting that set up for the current Greenstone 3 in $localgs3sourcehome"
  fi
  return 0
}

setGS3ENV() {

  echo "Setting up your environment for Greenstone3"
  ## main greenstone environment variables ##
  GSDL3SRCHOME="`pwd`"
  GSDL3HOME="$GSDL3SRCHOME/web"
  # not yet used
  GSDL3WEBHOME="$GSDL3SRCHOME/web"
  GSDL3DATAHOME="$GSDL3SRCHOME/data"
  export GSDL3HOME
  export GSDL3SRCHOME
  export GSDL3WEBHOME
  export GSDL3DATAHOME

  if test "x$GSDLOS" = "x" ; then
    GSDLOS=`uname -s | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
    # check for running bash under cygwin
    if test "`echo $GSDLOS | sed 's/cygwin//'`" != "$GSDLOS" ; then
      GSDLOS=windows
    fi 
  fi
  export GSDLOS
  echo "  - Exported:"
  echo "      GSDL3HOME    = $GSDL3HOME"
  echo "      GSDL3SRCHOME = $GSDL3SRCHOME"
  echo "      GSDL3WEBHOME = $GSDL3WEBHOME"
  echo "      GSDL3DATAHOME = $GSDL3DATAHOME"
  echo "      GSDLOS       = $GSDLOS"
  echo ""
  
  #change this if external tomcat
  TOMCAT_HOME="$GSDL3SRCHOME/packages/tomcat"

  ## adjustments to users (existing) environment ##

  #PATH
  addtopath PATH "$GSDL3SRCHOME/bin/script"
  addtopath PATH "$GSDL3SRCHOME/bin"
  echo "  - Adjusted PATH"
  if [ "$DEBUG" = "true" ] ; then
    echo "     = $PATH"
  fi

  #MANPATH
  addtopath MANPATH "$GSDL3SRCHOME/doc/man"
  echo "  - Adjusted MANPATH"
  if [ "$DEBUG" = "true" ] ; then
    echo "     = $MANPATH"
  fi
 
  #CLASSPATH
  addtopath CLASSPATH "."
  addtopath CLASSPATH "$GSDL3HOME/WEB-INF/classes"
  addtopath CLASSPATH "$GSDL3SRCHOME/resources/java"
  addtopath CLASSPATH "$GSDL3SRCHOME/cp.jar"

  # Greenstone JAR files
#  for JARFILE in "$GSDL3HOME/WEB-INF/lib"/*.jar; do
#      addtopath CLASSPATH "$JARFILE"
#  done
  
  # Tomcat jar files
#  if test -d "$TOMCAT_HOME"/lib ; then
#  for JARFILE in "$TOMCAT_HOME"/lib/*.jar; do
#    addtopath CLASSPATH "$JARFILE"
#  done    
#  fi

  echo "  - Adjusted CLASSPATH"
  if [ "$DEBUG" = "true" ] ; then
    echo "     = $CLASSPATH"
  fi

  #LD_LIBRARY_PATH
  addtopath LD_LIBRARY_PATH "$GSDL3SRCHOME/lib/jni"
  addtopath DYLD_LIBRARY_PATH "$GSDL3SRCHOME/lib/jni"
  echo "  - Adjusted LD_LIBRARY_PATH"
  if [ "$DEBUG" = "true" ] ; then
    echo "     = $LD_LIBRARY_PATH"
  fi

  echo "  - Adjusted DYLD_LIBRARY_PATH"
  if [ "$DEBUG" = "true" ] ; then
    echo "     = $DYLD_LIBRARY_PATH"
  fi

  #ImageMagick - we no longer set up imagemagick in the environment
  # instead, we call it using gs-magick.pl (in gs2build/bin/script)
  # which sets up its environment then runs it
  # eg gs-magick.pl convert -help
  #if test -d "$GSDL3SRCHOME/gs2build/bin/$GSDLOS/imagemagick" ; then
  #  addtopath PATH "$GSDL3SRCHOME/gs2build/bin/$GSDLOS/imagemagick/bin"
  #  MAGICK_HOME="$GSDL3SRCHOME/gs2build/bin/$GSDLOS/imagemagick"
  #  export MAGICK_HOME
  #  if test "$GSDLOS" = "linux"; then
  #    addtopath LD_LIBRARY_PATH "$GSDL3SRCHOME/gs2build/bin/$GSDLOS/imagemagick/lib"
  #  elif test "$GSDLOS" = "darwin"; then
  #    addtopath DYLD_LIBRARY_PATH "$GSDL3SRCHOME/gs2build/bin/$GSDLOS/imagemagick/lib"
  #  fi
  #  echo "  - Setup ImageMagick"
  #fi

  #Ghostscript
  if test -d "$GSDL3SRCHOME/gs2build/bin/$GSDLOS/ghostscript"; then
    addtopath PATH "$GSDL3SRCHOME/gs2build/bin/$GSDLOS/ghostscript/bin"
    GS_LIB="$GSDL3SRCHOME/gs2build/bin/$GSDLOS/ghostscript/share/ghostscript/8.63/lib"
    export GS_LIB
    GS_FONTPATH="$GSDL3SRCHOME/gs2build/bin/$GSDLOS/ghostscript/share/ghostscript/8.63/Resource/Font"
    export GS_FONTPATH
    echo "  - Setup GhostScript"
  fi

  #wvWare 
  # wvWare's environment is now set up by bin/script/wvware.pl
  # The wvware.pl script can be called from the cmdline to perform wvware tasks.
  # GLI calls gsConvert.pl which calls wvware.pl to similarly perform wvware tasks.
#  if test -d "$GSDL3SRCHOME/gs2build/bin/$GSDLOS/wv"; then
#    if test "$GSDLOS" = "linux"; then
#      addtopath LD_LIBRARY_PATH "$GSDL3SRCHOME/gs2build/bin/$GSDLOS/wv/lib"
#    elif test "$GSDLOS" = "darwin"; then
#      addtopath DYLD_LIBRARY_PATH "$GSDL3SRCHOME/gs2build/bin/$GSDLOS/wv/lib"
#    fi
#    echo "  - Setup wvWare"
#  fi

}

# Greenstone now relies on our version of perl-with-cpan
checkPerl() {
  echo ""
  echo "Checking for Perl"
    
    if [ -z "$GSPERL_WITH_CPAN_HOME" ] ; then 
        echo "  Greenstone needs Perl with many cpan packages installed."
        echo "  We provide a self contained Perl version with all the necessary packages."
        echo "  To install it, please cd to the ext-cli folder and run" 
        echo "      './get-selfcontained-perl-with-cpan.sh'"
        echo "  Then run 'source ./SETUP-CLI.sh'in the same folder"
        echo ""
        echo "  If you really want to use your system Perl, and don't want "
        echo "  to see this warning all the time, please set"
        echo "  GSPERL_WITH_CPAN_HOME to the location of your Perl eg /usr"
        echo ""
        return 1;
    else
        echo "  - Using Perl installed at $GSPERL_WITH_CPAN_HOME"

        # Unfortunately, checkJava breaks the PATH ordering when it prepends /usr/bin to PATH
        # as this overrides the perl-with-cpan prepended earlier by gs2build/setup.bash.
        # This means the ultimate perl found is the one at /usr/bin, which defeats the purpose
        # of having a perl-with-cpan.
        # Ugly, but prepend GSPERL_WITH_CPAN_HOME/bin again to PATH after removing it:
        #
        # https://unix.stackexchange.com/questions/108873/removing-a-directory-from-path
        # https://askubuntu.com/questions/76808/how-do-i-use-variables-in-a-sed-command
        # The single quotes around the variable inside the sed regex is necessary
        # The double quotes may protect against any spaces in the variable's path 
        PATH=$(echo "$PATH" | sed -e 's@'"$GSPERL_WITH_CPAN_HOME"'/bin\(:\|$\)@@g')
        echo "    Prepending $GSPERL_WITH_CPAN_HOME/bin to PATH again after removing it from PATH" 
        export PATH=$GSPERL_WITH_CPAN_HOME/bin:$PATH
        export PERLPATH=$GSPERL_WITH_CPAN_HOME/bin
        return 0;
    fi
}

checkJava() {
    # Check for JAVA_HOME (JDK)
    #   if set then we are done (as it would have been added to path already)
    # else
    #   if BUNDLED_JRE exists
    #     then set JRE_HOME to BUNDLED_JRE
    #     and add on slash JRE_HOME/bin and prepend this to PATH
    #     and set JAVA_HOME to JRE_HOME

  BUNDLED_JRE="`pwd`/packages/jre"
  PRIORITY_HINT=$BUNDLED_JRE

  using_bundled_jre=0
  
  # TODO chatgpt: spaces in java_home
  # In a bash script, if I want to update my $PATH with $JAVA_HOME/bin, where $PATH and
  # $JAVA_HOME are both locations that may contain spaces in them, what's the best way to do it?
  # Googled: when exporting variable, how to preserve spaces in PATH in bash
  if [ "x$JAVA_HOME" != "x" ] ; then
      # Evidence that this is a developer because they set JAVA_HOME deliberately
      echo "Found JAVA_HOME at $JAVA_HOME. "
      #echo "And adding \$JAVA_HOME/bin to \$PATH"
      #export PATH="$JAVA_HOME/bin:$PATH"
  elif [ -d "$BUNDLED_JRE" ] ; then
      if [ "x$JRE_HOME" = "x" ] ; then
	  # If we get to here, then this is the regular case for a GS binary we want to support
	  echo "Setting JRE_HOME to the bundled JRE_HOME at $BUNDLED_JRE"
	  export JRE_HOME="$BUNDLED_JRE"
	  using_bundled_jre=1
	  addtopath PATH "$JRE_HOME/bin"
      else
	  # Evidence of a developer trying to test a GS installed version
	  # but for some reason wish to explicitly control the JRE used to not use the bundled one
	  echo "Detected JRE_HOME as $JRE_HOME."
	  # Since the user's deliberately set JRE_HOME, help search4j favour this over BUNDLED_JRE
	  PRIORITY_HINT="$JRE_HOME"
      fi
      #echo "Adding \$JRE_HOME/bin to \$PATH"
      echo "And setting JAVA_HOME to the JRE_HOME found, since Ant needs JAVA_HOME set"
      export JAVA_HOME="$JRE_HOME"
      #export PATH="$JRE_HOME/bin:$PATH"
  fi
  

# I feel like we don't need any of the rest of this anymore.
# we are a binary - use bundled jre
# we are a source with ext-cli - use that java
# we are a source and not using ext-cli - user must set JAVA_HOME and add it to PATH in local/gs3-setup files.
# maybe we keep the bitness test?

  # Now the Greenstone 3.12 has been released, we are standardizing on the 'ext-cli/selfcontained' approach
  # This simplifies life set up on MacOS, where historically it's shipped with Java, then it wasn't, and at
  # some later point mucked around with how you found out where the Java was installed on the Mac.

  # Moving forward: on a Mac, you are either
  #  (i)  working with an installed GS3 which comes with a pre-bundled JRE; or
  #  (ii) working with a ext/selfcontained-jdk

  # For either situation, the end result is the same.  The *above* logic is sufficent to determine where Java
  # is => no longer need to do the following logic block of code
  
#  if [ "$GSDLOS" = "darwin" ] ; then
#      if [ $using_bundled_jre = 0 ]; then
#	  # From Mac Monterey (major kernel version 21) onwards, can do: export JAVA_HOME=$(/usr/libexec/java_home)
#	  # uname -r returns full kernel version number. Truncate to major version number (before 1st period mark)
#	  kernel_major_version=`uname -r | cut -d '.' -f 1`
#	  
#	  if [[ $kernel_major_version -ge 21 ]]; then
#	      #echo "@@@ darwin major kernel version: $kernel_major_version"
#	      # https://stackoverflow.com/questions/72451098/how-to-set-java-home-in-macos-monterey-when-usr-libexec-java-home-returns-an-er
#	      TMP_JAVA_HOME=$(/usr/libexec/java_home /dev/null 2>&1)
#	      if [ $? = 0 ] ; then
#		  # TODO: export JAVA_HOME??? No: we're not sure we're ultimately settling with this JAVA_HOME we've found
#		  # And setupJavaAt() will set actual JAVA_HOME determined, besides adding bin to PATH
#		  JAVA_HOME="$TMP_JAVA_HOME"
#	      fi
#	  fi
#	  
#	  # try $JAVA_HOME first, if it is set
#	  if [ "x$JAVA_HOME" != "x" ] && [ -d "$JAVA_HOME" ] ; then
#	      PRIORITY_HINT=$JAVA_HOME    
#	  elif [ ! -d "$PRIORITY_HINT" ] ; then
#	      #we test for the existence of bundled_jre - will be present in binary release. Use that if it is there as we know that it works with GS
#	      # but if it's not there, try the following:
#	      # this will print out the path to java. Old code used as fallback,
#	      # but this is not valid for Mojave, Catalina (probably Big Sur too) and Monterey. So kernel versions 18 and later.
#	      if [[ $kernel_major_version -lt 18 ]]; then
#		  PRIORITY_HINT=`/usr/libexec/java_home`
#		  if [ ! -d "$PRIORITY_HINT" ] ; then
#		      PRIORITY_HINT=/System/Library/Frameworks/JavaVM.framework/Home
#		  fi
#	      fi
#	  fi
#     fi
#  fi

  if [ "$DEBUG" = "true" ] ; then echo "**********************************************"; fi

#  if [ $using_bundled_jre = 1 ]; then
#      echo "Found bundled jre, not using search4j."
#      echo "   If you want to use search4j, rename packages/jre to packages/unused-jre"
#      return
#  fi
  
  # If the file utility exists, use it to determine the bitness of this GS3,
  # particularly of this GS3's lib/jni/libgdbmjava.so/jnilib, since we prefer a matching java
  # If any executable doesn't exist, the return value is 127.
  # If file utility exists, then 0 is returned on successful execution, 1 is an error exit code
  # Running file without arg returns 1 therefore.

  # Determine the bitness of this GS3 installation, by running:
  # `file lib/jni/libgdbmjava.so/jnilib`
  # Output:
  #    lib/jni/libgdbmjava.so: ELF 64-bit LSB  shared object, x86-64, version 1 (SYSV),
  #    dynamically linked, BuildID[sha1]=5ae42cf69275408bdce97697d69e9e6fd481420d, not stripped
  # On 32-bit linux, the output will contain "lib/jni/libgdbmjava.so: ELF 32-bit ..."
  # Check output string contains bitness: http://stackoverflow.com/questions/229551/string-contains-in-bash

  echo ""  
  command -v file > /dev/null 2>&1
  file_cmd_status=$?
  
  JNITESTFILE="$GSDL3SRCHOME/lib/jni/libgdbmjava.so"
  if test "$GSDLOS" = "darwin"; then
     JNITESTFILE="$GSDL3SRCHOME/lib/jni/libgdbmjava.jnilib"
  fi

  if [ $file_cmd_status != 0 ] ; then
      if [ "$DEBUG" = "true" ] ; then 
	  echo "    'file' utility not found installed on this unix-based system."
	  echo "    Unable to use 'file' utility to determine bitness of this GS3 to see if it matches that of any Java found."
      fi
      bitness=-1
  elif [ ! -f "$JNITESTFILE" ] ; then
      # the file we want to test the bitness of, to determine GS3's bitness by, doesn't exist yet
#      echo "    $JNITESTFILE is not found, unable to determine bitness of this Greenstone3"
      echo "  - No JNI files detected.  Skipping Java bitness test"
      bitness=-1
  else
      #bitness=`file $JNITESTFILE | sed 's/^.* \([0-9]\+-bit\).*$/\1/'`
      # one-or-more regex to get one or more digits was not working. Dr Bainbridge fixed as below
      #bitness=`file $JNITESTFILE | sed 's/^.* \([0-9][0-9]-bit\).*$/\1/'`
      # The following also does one-or-more and works on the command line and should support 3 digit bitness
      # https://stackoverflow.com/questions/12101440/one-or-more-occurrences-not-working-with-sed-command
      bitness=`file $JNITESTFILE | sed 's/^.* \([0-9]\{1,\}-bit\).*$/\1/'`
      if [ $bitness = "64-bit" ] ; then
	  bitness=64
#	  echo "The installed Greenstone is $bitness bit"
      elif [ $bitness = "32-bit" ] ; then
	  bitness=32
#	  echo "The installed Greenstone is $bitness bit"
      else
	  bitness=-1
	  echo "WARNING: Greenstone installation is of unknown bitness. \"$bitness\" is neither '32-bit' nor '64-bit'"
      fi
      echo "JNI bitness test: $bitness"
  fi

  # If search4j is present, use it to locate a java.
  # If search4j finds a Java, then:
  # - If its bitness doesn't match and there's a bundled jre, use the bundled jre instead.
  # - If its bitness doesn't match and there's no bundled jre, use the java found by search4j anyway,
  # we'll print a warning about this bitness mismatch at the end

  echo ""
  echo "Checking for Java"
  
  javaset=false
  if [ -x bin/search4j ] ; then
      FOUNDJAVAHOME="`bin/search4j -d -p \"$PRIORITY_HINT\" -m $java_min_version`"
      javahome_retval=$?
      FOUNDJREHOME="`bin/search4j -r -p \"$PRIORITY_HINT\" -m $java_min_version`"
      jrehome_retval=$?
  fi

  # 1. check the bitness of any JDK java found by search4j, and use if appropriate
  if [ "$javahome_retval" = "0" ] ; then
      setJavaIfOK "$DEBUG" "$bitness" "$FOUNDJAVAHOME" "JDK"
      if [ "$?" = "0" ] ; then javaset="true"; fi
  fi

  # 2. check the bitness of any JRE java found by search4j, and use if appropriate
  if [ "$javaset" != "true" ] && [ "$jrehome_retval" = "0" ] ; then
      setJavaIfOK "$DEBUG" "$bitness" "$FOUNDJREHOME" "JRE"
      if [ "$?" = "0" ] ; then javaset="true"; fi
  fi
  
  # 3. check the bitness of any bundled JRE, and use if appropriate
  # For linux, the bundled JRE ought to be of a bitness matching this OS.
  if [ "$javaset" != "true" ] && [ -d "$BUNDLED_JRE" ] ; then
      setJavaIfOK "$DEBUG" "$bitness" "$BUNDLED_JRE" "Bundled-JRE"
      if [ "$?" = "0" ] ; then javaset="true"; fi
  fi


  # 4. None of the java found so far (via search4j, bundled_jre), if any, may have matched bitness wise
  # So, fall back to using whichever is available in sequence anyway.
  # We'll print a warning of bitness mismatch later

  if [ "$javaset" != "true" ] ; then
      # go with any JAVA_HOME else JRE_HOME that search4j found, else with any bundled JRE if present
      if [ "$javahome_retval" = "0" ] ; then
	  setupJavaAt "$FOUNDJAVAHOME" "JDK"
	  javaset=true
      elif [ "$jrehome_retval" = "0" ] ; then
	  setupJavaAt "$FOUNDJREHOME" "JRE"
	  javaset=true
      elif [ -d "$BUNDLED_JRE" ] ; then
	  # bundled JRE should be >= than minimum version of java required
	  setupJavaAt "$BUNDLED_JRE" "JRE"
	  javaset=true
      fi
  fi

  # 5. lastly, manually check if java already setup. Could be the case if search4j didn't exist
  if [ "$javaset" != "true" ] ; then

    if [ -x bin/search4j ] ; then

      # no suitable java could be found by search4j
      echo "  - Warning: Search4j failed to locate java $java_min_version or greater"	  
      echo "             Please set JAVA_HOME or JRE_HOME to point to an appropriate java"
      echo "             And add JAVA_HOME/bin or JRE_HOME/bin to your PATH"

    else
      # search4j wasn't present, and no bundled JRE, so check JAVA_HOME or JRE_HOME manually
      #echo "*** Could not find an appropriate JDK or JRE java"
      #echo "*** Attempting to use JAVA_HOME else JRE_HOME in the environment"
      echo "  - search4j' not detected.  Checking for Java explicitly set through environment variables"
      if [ "x$JAVA_HOME" != "x" ] && [ "`which java`" = "$JAVA_HOME/bin/java" ] ; then
	  echo "  - Using Java at $JAVA_HOME"
	  if [ "$DEBUG" = "true" ] ; then
	      echo "  - Detected Java version: `$JAVA_HOME/bin/java -version 2>&1 | head -n 1`"
	      echo "  - Note that Greenstone requires Java 1.5 or greater"
#	      echo "  - WARNING: Greenstone has not checked the version number of this java installation"
#    	      echo "             The source distribution of Greenstone3 requires java 1.5 or greater"
	      #	      echo "             (SVN users may still use java 1.4)"
	  fi
      elif [ "x$JRE_HOME" != "x" ] && [ "`which java`" = "$JRE_HOME/bin/java" ] ; then
	  echo "  - Using java at $JRE_HOME"
	  if [ "$DEBUG" = "true" ] ; then
	      echo "  - Detected Java version: `$JAVA_HOME/bin/java -version 2>&1 | head -n 1`"
	      echo "  - Note that Greenstone requires Java 1.5 or greater"	  
#	      echo "  - WARNING: Greenstone has not checked the version number of this java installation"
#	      echo "             The source distribution of Greenstone3 requires java 1.5 or greater"
#	      echo "             (SVN users may still use java 1.4)"
	  fi
      #failing all that, print a warning
      else
	  echo "  - Did not detect 'java' via JAVA_HOME or JRE_HOME"
	  echo "Testing for 'java' on PATH"
	  command -v java
	  if [ $? != 0 ] ; then
              #no suitable java exists
	      echo "  - Error: Failed to locate 'java'"
	      echo "           Please set JAVA_HOME or JRE_HOME to point to an appropriate java"
	      echo "           And add JAVA_HOME/bin or JRE_HOME/bin to your PATH"
	      return
	  fi
      fi
    fi
  fi

  # If we know the bitness of this GS3 installation, then warn if there's a mismatch
  # with the bitness of the Java found

  if [ "$bitness" != "-1" ] ; then
      if [ "x$JAVA_HOME" != "x" ] ; then
	  JAVA_FOUND=$JAVA_HOME
      elif [ "x$JRE_HOME" != "x" ] ; then
	  JAVA_FOUND=$JRE_HOME
      fi
      checkJavaBitnessAgainstGSBitness "$JAVA_FOUND" "$bitness"
      if [ "$?" = "1" ] ; then
	  echo "*** WARNING: Detected mismatch between the bit-ness of your GS installation ($bitness bit)"
	  echo "*** and the Java found at $JAVA_FOUND/bin/java"
	  echo "*** Continuing with this Java anyway:"
	  echo "*** This will only affect MG/MGPP collections for searching, and GDBM database collections"
	  echo "*** Else set JAVA_HOME or JRE_HOME to point to an appropriate $bitness bit Java"
	  echo "*** Or recompile GS with your system Java:"
	  if [ "x$JAVA_HOME" != "x" ] ; then
	      echo "*** JAVA_HOME at $JAVA_HOME"
	  else
	      echo "*** JRE_HOME at $JRE_HOME"
	  fi
      fi
  fi

  if [ "$DEBUG" = "true" ] ; then echo "**********************************************"; fi

}

# http://www.linuxjournal.com/content/return-values-bash-functions
setJavaIfOK() {

    if [ "$DEBUG" = "true" ] ; then echo "Testing java at $3"; fi

    DEBUG=$1
    bitness=$2
    PATHTOJAVA=$3
    JDKorJRE=$4

    checkJavaBitnessAgainstGSBitness "$PATHTOJAVA" "$bitness"
    check_status=$?

    isjavaset=false

    if [ "$check_status" = "0" ] ; then
	# http://tldp.org/LDP/abs/html/comparison-ops.html
	if [ "$bitness" != "-1" ] && [ "$DEBUG" = "true" ] ; then
	    # java matches GS bitness
	    if [ "$JDKorJRE" = "Bundled-JRE" ] ; then
		echo "*** Changing to use Greenstone's $bitness-bit $JDKorJRE at $PATHTOJAVA"
	    else
		echo "    The detected $JDKorJRE at $PATHTOJAVA is a matching $bitness bit"
	    fi 
	fi
	setupJavaAt "$PATHTOJAVA" "$JDKorJRE"
	isjavaset=true
	
    elif [ "$bitness" != "-1" ] && [ "$DEBUG" = "true" ] ; then
	if [ "$JDKorJRE" = "Bundled-JRE" ] ; then
	    echo "    The $JDKorJRE java is an incompatible bit architecture"
	else
	    echo "    The detected $JDKorJRE java is an incompatible bit architecture"
	fi
    fi
    
    if [ "$isjavaset" = "true" ] ; then
	return 0 # success
    else
	return 1
    fi
}

# if bitness (parameter #2) is -1, then this function returns 0 (generally meaning success).
checkJavaBitnessAgainstGSBitness() {
#    if [ "$DEBUG" = "true" ] ; then echo "Testing bitness of java found at $java_installation"; fi
    java_installation="$1"
    bitness="$2"

    # bitness can be -1 if the 'file' utility could not be found to determine bitness
    # or if its output no longer prints "32-bit" or "64-bit". Should continue gracefully
    if [ "$bitness" = "-1" ] ; then
	return 0
    fi

    # now we can actually work out if the java install's bitness matches that of GS ($bitness)
    # java -d32 -version should return 0 if the Java is 32 bit, and 1 (failure) if the Java is 64 bit.
    # Likewise, java -d64 -version will return 0 if the Java is 64 bit, and 1 (failure) if the Java is 32 bit.
    `$java_installation/bin/java -d$bitness -version 2> /dev/null`

    if [ "$?" = "0" ] ; then
	return 0
    elif [ "$?" = "1" ] ; then
	
        # Newer Java's don't support -d, so resort to using dedicated java-based program GS3 provides
	# for reporting Java bitness
	java_bitness=`java -jar "$GSDL3SRCHOME/lib/java/display-java-bitness.jar"`
        if [ $java_bitness = "$bitness" ] ; then
	    return 0
	else
	    return 1
	fi
    else
	echo "*** Problem determining bitness of java using java at $java_installation"
	return $?
    fi
}


setupJavaAt() {

  # check the second parameter if non-null
  if [ -n "$2" ] && [ "$2" = "JRE" ] ; then
    export JRE_HOME="$1"
    addtopath PATH "$JRE_HOME/bin"

    # ant needs a JAVA_HOME, so set that too, to the JRE
    export JAVA_HOME="$JRE_HOME"
   
    BUNDLED_JRE="`pwd`/packages/jre"    
    if [ "$JRE_HOME" = "$BUNDLED_JRE" ] ; then
	msg="the bundled"
    fi
    
    echo "  - Exported JRE_HOME and JAVA_HOME to $msg $JRE_HOME"
  else
    export JAVA_HOME="$1"
    addtopath PATH "$JAVA_HOME/bin"
    echo "  - ***Exported JAVA_HOME to $JAVA_HOME"
  fi

  
}

displayVars() {
	echo "GSDL3SRCHOME : $GSDL3SRCHOME"
	echo "GSDL3HOME    : $GSDL3HOME"
        echo "GSDL3WEBHOME = $GSDL3WEBHOME"
        echo "GSDL3DATAHOME = $GSDL3DATAHOME"
	# No RUNJAVA variable on unix
	#echo "JAVA         : $RUNJAVA"
	if [ "x$JAVA_HOME" != "x" ] ; then
	  echo "JAVA_HOME    : $JAVA_HOME"
	fi
	if [ "x$JRE_HOME" != "x" ] ; then
	  echo "JRE_HOME     : $JRE_HOME"
	fi
	echo "PERL         : $PERLPATH"

	if [ "x$ANT_HOME" = "x" ] ; then
	   echo ""
	   echo "ANT_HOME is not yet set."
	   echo "Please make sure you have Ant version 1.8.2 or higher installed"
	   echo "Then set ANT_HOME to the Ant installation folder"
	   echo "and add the path to its bin folder to the PATH environment variable"
	else
	   echo "ANT_HOME     : $ANT_HOME"
	fi
	#echo "PATH         : $PATH"
	echo ""
}

pauseAndExit(){
 echo -n "Please press any key to continue... "
 read 
}

isinpath() {
  for file in `echo $1 | sed 's/:/ /g'`; do
    if [ "$file" = "$2" ] ; then
      echo true
      return
    fi
  done
  echo false
}

addtopath() {
  eval "PV=\$$1"
  #echo "@@@ env var: $PV"
  #echo "$1 += $2"
  if [ "x$PV" = "x" ] ; then
      # Gemini corrected this line for preserving spaces, explaining:
      # "By escaping the dollar sign (\$2), Bash writes the literal text $2 into the command string
      # instead of expanding it early. When eval runs, it expands nicely with quotes intact."
      cmd="$1=\"\$2\""
      eval "$cmd"
  elif [[ ":$PV:" == *":$2:"* ]]; then
    echo "Directory $2 exists in env var $1. Not prepending."
  else
    echo "Prepending to env var $1"
    cmd="$1=\"$2:\$$1\""
    eval "$cmd"
  fi
  eval "export $1"
}

# Note: use return not exit from a sourced script otherwise it kills the shell
testSource
if [ "$?" = "1" ] ; then
  return
fi

testAlreadySourced
if [ "$?" = "1" ] ; then
  return
fi

if test -e ext-cli/SETUP-CLI.sh ; then
  echo ""
  echo "Sourcing ext-cli/SETUP-CLI.sh"
  cd ext-cli; . ./SETUP-CLI.sh ; cd ..
else
  echo "WARNING: No ext-cli/SETUP-CLI.sh found"
fi


setGS3ENV

if test -e gs2build/setup.bash ; then 
  echo ""
  echo "Sourcing gs2build/setup.bash"
  cd gs2build ; . ./setup.bash ; cd ..
else
    echo "WARNING: No gs2build/setup.bash found"
fi


if test "x$gsopt_noexts" != "x1" ; then
    if test -e ext ; then
	for gsdl_ext in ext/* ; do
	    if [ -d $gsdl_ext ] ; then
		if [[ "$gsdl_ext" == *.inactive ]]; then
		    echo "Skipping inactive extension $gsdl_ext"
		    continue
		fi
		cd $gsdl_ext > /dev/null
		if test -e gs3-setup.sh ; then 
		    . ./gs3-setup.sh 
		elif test -e setup.bash ; then 
		    . ./setup.bash 
		fi 
		cd ../..  
	    fi
	done
    fi
fi

if test -e local ; then
  if test -e local/gs3-setup.sh ; then 
    echo ""
    echo "Sourcing local/gs3-setup.sh"
    echo ""
    cd local ; . ./gs3-setup.sh ; cd ..
  fi
fi


checkJava
echo ""


# If webswing-server.war is present, then (for X-Window systems)
# work out if the system is capable of running webswing
#
# => If it can, but is a headless server, then needs 'xvfb-run' 

export CATALINA_START_RUNJAVA=""

if [ -f packages/tomcat/webapps/webswing-server.war ] ; then

    if [ "$GSDLOS" = "linux" ] && [ "x$DISPLAY" = "x" ] ; then
	# a headless linux server
	# => need xvfb-run to be able to operate webswing-server.war
	
	command -v xvfb-run > /dev/null 2>&1
	if [ $? = 0 ] ; then
	    echo "Setting CATALINA_START_RUNJAVA to '$GSDL3SRCHOME/bin/script/xvfb-run-java'"
	    echo "  => Allows webswing-server.war to graphically render on headless server"
	    export CATALINA_START_RUNJAVA="$GSDL3SRCHOME/bin/script/xvfb-run-java"
	else
	    echo "Warning: No DISPLAY variable set     => looks like a headless server"
	    echo "         Unable to detect 'xvfb-run' => webswing-server.war unlikely to work"
	    echo "         ----"
	    echo "         To install xvfb on Debian based distros (e.g. Ubuntu): "
	    echo "             sudo apt-get install xvfb"
	    echo "         (You might also need to apt-get install: libxrender1 libxtst6 libxi6)"
	    echo "         ----"
	fi
	echo ""
    fi
fi


# Ant
echo "Checking for Ant"

# Note 1: No longer need to print out info about minimum version of
#  Ant needed for Greenstone3 (v1.8.2 at the time of updating this
#  comment!), as this is now explicitly tested for in the build.xml
#  file, and an error message generated if not new enough

# Note 2: The setting of ANT_ARGS to '-noclasspath' flag below is to
#   void "cross-contamination' between this setup file -- which sets
#   CLASSPATH to include all the jars in <gsdl3srchome>web/WEB-INF,
#   including an ant.jar -- and what is needed to cleanly run the
#   'ant' script and have it find the matching 'ant.jar' that goes
#   with it (i.e. is the same version).  For example we want the
#   system installed /usr/bin/ant to find /usr/share/ant/lib/ant.jar
#
#   Undesirable behaviour can occur, however, when the 'ant' that is
#   run is the one found on PATH, and a different ant.jar is found (as
#   can occur when CLASSPATH is set).  For this pattern of running the
#   'ant' script the 'ant.jar' that is in Greenstone's web/WEB-INF
#   area is found.  This Greenstone ant.jar file (at the time of
#   writing) is for ant v.1.8.2, and causes some of the Java
#   properities ant uses to changed.  Even if your installed 'ant' is
#   (say v1.10.9) and the JDK you are running is JDK11, as a
#   consequence of finding the older ant.jar file, ant.version is set
#   to 1.8.2 and ant.java.version to 1.7.  As a consequence of this,
#   the Greenstone3 build.xml fails to run as its minimum Java version
#   needs to be >=1.8
#
#   In looking at how to address this issue, updating the version of ant.jar
#   was considered.  However, taking this approach means there will aways be
#   a risk of a version mismatch between a system installed 'ant' and
#   the version of ant.jar Greenstone includes.
#
#   The approach taken here, then, is to more carefully control the
#   launching of ant.  By setting ANT_ARGS to -noclasspath, the 'ant'
#   script is directed not to use CLASSPATH, thereby avoidig the
#   cross-contamination problem.
#
#   Of further note, in the event ANT_HONE is set, then the situation
#   we are in is much simpler, as the cross-contamination problem
#   doesn't arise.  This is because the 'ant' script explicitly sets
#   ANT_LIB, based on ANT_HOME, to explicitly pick out ant.jar file
#   that goes along with the script.
#

if [ -x "$GSDL3SRCHOME/packages/ant/bin/ant" ] ; then
  ANT_HOME="$GSDL3SRCHOME/packages/ant"
  export ANT_HOME
  addtopath PATH "$ANT_HOME/bin"
  echo "  - Setup Greenstone ant ($GSDL3SRCHOME/packages/ant)"
else
  if [ "x$ANT_HOME" != "x" ] ; then
    #addtopath PATH "$ANT_HOME/bin"
    echo "  - `ant -version`"
  else
    # which ant > /dev/null 2>&1
    # Posix friendly way to determine if a program exists:
    #   https://stackoverflow.com/questions/592620/how-can-i-check-if-a-program-exists-from-a-bash-script
    command -v ant > /dev/null 2>&1
      
    if [ "$?" = "0" ] ; then
      echo "  - System install ant detected"

      if [ "x$ANT_ARGS" = "x" ] ; then
	  ANT_ARGS="-noclasspath"
      else
	  ANT_ARGS="-noclasspath $ANT_ARGS"
      fi
      export ANT_ARGS

      echo "  - `ant -version`"

    else
      echo "  - WARNING: Failed to find 'ant'"
    fi
  fi
fi

checkPerl
#- now its just a warning
#if [ "$?" = "1" ] ; then
#  return 
#fi

# The batch script prints out some key variables, so let's do the same in this .sh file
displayVars


echo "done"

