#!/usr/bin/env bash
# Gradle wrapper that resolves a JDK via mise before delegating to ./gradlew.
#
# Why this exists: ./gradlew is a shell script that needs a JVM to launch
# itself, so it cannot be fixed by org.gradle.java.home in gradle.properties.
# This project has no JDK on PATH, so agents must go through this script.
#
#   ./jaigradle check      # run all tests
#   ./jaigradle test       # unit tests only
#
# The JDK version is pinned in ./mise.toml. It must be 21+: the IntelliJ
# Platform test-framework jars are Java 21 bytecode (class major version 65)
# and throw UnsupportedClassVersionError on 17.
set -euo pipefail
cd "$(dirname "$0")"
source ./gradle-lock.sh

# `--stop` is an explicit recovery operation; it must be able to stop a
# daemon even when a stale lock was left by an interrupted run.
if [[ "${1:-}" != "--stop" ]]; then
  jai_gradle_lock_acquire
  trap jai_gradle_lock_release EXIT
  trap 'exit 130' INT
  trap 'exit 143' TERM
fi

status=0
if command -v mise >/dev/null 2>&1; then
  mise exec -- ./gradlew "$@" || status=$?
else

# Fallback: mise is not installed. Try an already-set JAVA_HOME, then any
# JDK 21 that Gradle has auto-provisioned.
if [ ! -x "${JAVA_HOME:-}/bin/java" ]; then
  for candidate in "$HOME"/.gradle/jdks/*/*/Contents/Home "$HOME"/.gradle/jdks/*/*; do
    if [ -x "$candidate/bin/java" ]; then
      export JAVA_HOME="$candidate"
      break
    fi
  done
fi

if [ ! -x "${JAVA_HOME:-}/bin/java" ]; then
  echo "jaigradle: no JDK found. Install mise (https://mise.jdx.dev) and run 'mise install'," >&2
  echo "           or set JAVA_HOME to a JDK 21+ installation." >&2
  exit 1
fi

  ./gradlew "$@" || status=$?
fi

jai_gradle_lock_release
trap - EXIT INT TERM
exit "$status"
