#!/usr/bin/env bash
# gradle.sh — afk pre-spawn detector for Gradle projects.
#
# Applies when a build.gradle* file exists at PROJECT_ROOT AND the
# operator has opted in by setting RED_AFK_GRADLE_USER_HOME_BASE. Exports
# GRADLE_USER_HOME=${RED_AFK_GRADLE_USER_HOME_BASE}/slot-${RED_AFK_SLOT} so each
# worker slot gets its own Gradle home (caches, daemons, lockfiles).
#
# Opt-in by env var is deliberate: we will not claim a path on the
# user's filesystem without their consent. Without
# RED_AFK_GRADLE_USER_HOME_BASE the detector is a no-op (exit 1).
#
# Exit codes:
#   1 — not a Gradle project, or RED_AFK_GRADLE_USER_HOME_BASE unset.
#   0 — applies; KEY=value line written to $RED_AFK_HOOK_ENV_FILE.

set -u

project_root="${PROJECT_ROOT:-$(pwd)}"

has_gradle_build=false
for candidate in "$project_root"/build.gradle*; do
  [ -f "$candidate" ] || continue
  has_gradle_build=true
  break
done
[ "$has_gradle_build" = true ] || exit 1

[ -n "${RED_AFK_GRADLE_USER_HOME_BASE:-}" ] || exit 1

slot="${RED_AFK_SLOT:-0}"
home_dir="${RED_AFK_GRADLE_USER_HOME_BASE}/slot-${slot}"

mkdir -p "$home_dir"

: "${RED_AFK_HOOK_ENV_FILE:?RED_AFK_HOOK_ENV_FILE not set}"
printf 'GRADLE_USER_HOME=%s\n' "$home_dir" >> "$RED_AFK_HOOK_ENV_FILE"
exit 0
