# install4j doesn't bother to resolve symlinks when it finds java, so if it finds
# java at /usr/bin/java it will happily decide that "/usr" is java_home. It then passes along
# a -Djava.ext.dirs=/usr/lib/ext to the installer JVM, a directory that doesn't exist. This breaks
# pingbacks to HTTPS servers because one of the JARs in ext is the sunjce_provider.jar which
# contains the security related classes used by the secure socket implementation in Java.
#
# This script fragment attempts to resolve the symlink, and test the resulting
# directory - if it doesn't work for some reason it'll go ahead and use the original
# setting

debug_log() {
    if [ -n "$INSTALL4J_DEBUG" ]; then
        echo $1
    fi
}

test_java_binary="$app_java_home/bin/java"
if [ -L "$test_java_binary" ]; then
  debug_log "Java binary at $test_java_binary is a symlink - trying to find real home"

  resolved_symlink=`readlink -f "$test_java_binary"`
  debug_log "... resolved symlink to $resolved_symlink"

  resolved_java_home=`expr "$resolved_symlink" : '\(.*\)/bin/java$'`
  bak_app_java_home=$app_java_home
  unset app_java_home

  debug_log "... trying $resolved_java_home with test_jvm"
  test_jvm $resolved_java_home

  if [ -z "$app_java_home" ]; then
    debug_log "Failed to fix java_home - setting back to $bak_app_java_home"
    app_java_home=$bak_app_java_home
    unset bak_app_java_home
  else
    debug_log "Fixed java_home to $app_java_home!"
  fi
fi