# Environment for Xcode build-phase scripts (sourced by the "Compile Kotlin/Native
# framework" run-script phase in project.yml).
#
# Xcode runs build phases with a minimal environment that does NOT include your
# interactive shell profile (~/.zprofile, ~/.zshrc, etc.), so a JDK that works in
# Terminal may be invisible to Gradle here — it then fails with:
#     Unable to locate a Java Runtime
#
# This file finds a JDK and exports JAVA_HOME. It only sets JAVA_HOME when it is
# not already set to a valid JDK, so an environment that already exports a working
# JAVA_HOME (for example CI via actions/setup-java) is left untouched.
#
# If none of the locations below match your machine, point at your JDK WITHOUT
# committing the change by creating iosApp/.xcode.env.local (it is git-ignored):
#     export JAVA_HOME=/path/to/your/jdk/Contents/Home
# The run-script phase sources .xcode.env.local AFTER this file, so it wins.

# A JAVA_HOME is only usable if it actually contains a java executable.
_xcode_env_is_valid_java_home() {
  [ -n "$1" ] && [ -x "$1/bin/java" ]
}

if ! _xcode_env_is_valid_java_home "$JAVA_HOME"; then
  JAVA_HOME=""
  # 1. macOS's java_home helper (JDKs in /Library/Java/JavaVirtualMachines).
  if [ -x /usr/libexec/java_home ]; then
    _candidate="$(/usr/libexec/java_home 2>/dev/null)"
    _xcode_env_is_valid_java_home "$_candidate" && JAVA_HOME="$_candidate"
  fi
  # 2. Common JDK install locations (Android Studio's bundled JBR, Homebrew, etc.).
  if [ -z "$JAVA_HOME" ]; then
    for _candidate in \
      "$HOME/Library/Java/JavaVirtualMachines"/*/Contents/Home \
      "/Applications/Android Studio.app/Contents/jbr/Contents/Home" \
      "/Applications/Android Studio Preview.app/Contents/jbr/Contents/Home" \
      "/opt/homebrew/opt/openjdk/libexec/openjdk.jdk/Contents/Home" \
      "/usr/local/opt/openjdk/libexec/openjdk.jdk/Contents/Home" \
      "/Library/Java/JavaVirtualMachines"/*/Contents/Home; do
      if _xcode_env_is_valid_java_home "$_candidate"; then
        JAVA_HOME="$_candidate"
        break
      fi
    done
  fi
  # 3. A java already on PATH (resolve the symlink to its JDK home).
  if [ -z "$JAVA_HOME" ]; then
    _java_bin="$(command -v java 2>/dev/null)"
    if [ -n "$_java_bin" ]; then
      _candidate="$(cd "$(dirname "$(readlink "$_java_bin" || echo "$_java_bin")")/.." 2>/dev/null && pwd)"
      _xcode_env_is_valid_java_home "$_candidate" && JAVA_HOME="$_candidate"
    fi
  fi
  export JAVA_HOME
fi
