#!/bin/sh
# xwpe-env -- print (or persist) the environment xwpe wants, in your shell's syntax.
#
# It locates (when present) Homebrew's keg-only clangd, an LTS JDK for Metals,
# and the Coursier app dir, and exposes XWPE_LIB so syntax highlighting + Help
# load when you run from the build tree without `sudo make install`.  Anything
# not installed is silently skipped, so the output is always safe to apply.
#
# Usage -- evaluate it, do not run it:
#
#   bash / zsh :  eval "$(sh contrib/xwpe-env)"
#   fish       :  sh contrib/xwpe-env --shell fish | source
#
# That applies it to the CURRENT shell only.  To make it PERMANENT (every new
# terminal), let the script add itself to your shell profile -- it writes the
# correct line with this script's ABSOLUTE path, and is idempotent:
#
#   sh contrib/xwpe-env --persist          # detects your shell from $SHELL
#   sh contrib/xwpe-env --persist --shell fish
#
# This is the brew-shellenv / direnv idiom: a tool that emits shell code rather
# than a list of exports you copy by hand.  Works on macOS and Linux.

set -eu

# --- parse args: --shell <flavour>, --persist -------------------------------
shell=
persist=0
while [ $# -gt 0 ]; do
  case "$1" in
    --persist)  persist=1 ;;
    --shell)    shell=${2:-}; shift ;;
    --shell=*)  shell=${1#--shell=} ;;
    *)          ;;
  esac
  shift
done
[ -n "$shell" ] || shell=$(basename "${SHELL:-sh}")

# Absolute path to THIS script (for the --persist line) and the checkout root.
self=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)/$(basename -- "$0")
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)

# --- emitters (POSIX `export` vs fish `set -gx`) ----------------------------
emit_var() {        # emit_var NAME VALUE
  case "$shell" in
    fish) printf 'set -gx %s "%s"\n' "$1" "$2" ;;
    *)    printf 'export %s="%s"\n'  "$1" "$2" ;;
  esac
}
emit_path() {       # emit_path DIR   -- prepend DIR to PATH
  case "$shell" in
    fish) printf 'set -gx PATH "%s" $PATH\n'  "$1" ;;
    *)    printf 'export PATH="%s:$PATH"\n'    "$1" ;;
  esac
}

# --- --persist: add the right line to the shell profile, once ---------------
persist_to_profile() {
  case "$shell" in
    fish) prof="${XDG_CONFIG_HOME:-$HOME/.config}/fish/config.fish"
          line="sh \"$self\" --shell fish | source" ;;
    zsh)  prof="$HOME/.zshrc"   ; line="eval \"\$(sh \"$self\")\"" ;;
    bash) prof="$HOME/.bashrc"  ; line="eval \"\$(sh \"$self\")\"" ;;
    *)    prof="$HOME/.profile" ; line="eval \"\$(sh \"$self\")\"" ;;
  esac
  mkdir -p "$(dirname -- "$prof")"
  [ -f "$prof" ] || : > "$prof"
  if grep -Fq "$self" "$prof" 2>/dev/null; then
    echo "xwpe-env: already set up in $prof (nothing to do)." >&2
    return 0
  fi
  {
    printf '\n# xwpe environment (added by: xwpe-env --persist)\n'
    printf '%s\n' "$line"
  } >> "$prof"
  echo "xwpe-env: added to $prof" >&2
  echo "  open a new terminal, or run: source '$prof'" >&2
}

if [ "$persist" = 1 ]; then
  persist_to_profile
  exit 0
fi

# --- XWPE_LIB: this checkout, so it runs uninstalled (the repo root) ----------
[ -f "$root/syntax_def" ] && emit_var XWPE_LIB "$root"

# --- Homebrew-provided language servers / JDK (no-op without brew) ------------
if command -v brew >/dev/null 2>&1; then
  llvm=$(brew --prefix llvm 2>/dev/null || true)        # clangd is keg-only
  [ -n "$llvm" ] && [ -x "$llvm/bin/clangd" ] && emit_path "$llvm/bin"
fi

# --- JAVA_HOME: an LTS JDK (21 preferred, then 17) for Metals ----------------
# Try, in order: Homebrew, the macOS java_home registry, the Linux /usr/lib/jvm
# layout (Debian/Ubuntu/Fedora/Arch).  First match wins; absent -> nothing.
jhome=
if command -v brew >/dev/null 2>&1; then
  for f in openjdk@21 openjdk@17; do
    p=$(brew --prefix "$f" 2>/dev/null || true)
    [ -n "$p" ] && [ -d "$p/libexec/openjdk.jdk/Contents/Home" ] && {
      jhome="$p/libexec/openjdk.jdk/Contents/Home"; break; }
  done
fi
if [ -z "$jhome" ] && [ -x /usr/libexec/java_home ]; then   # macOS registry
  for v in 21 17; do
    p=$(/usr/libexec/java_home -v "$v" 2>/dev/null || true)
    [ -n "$p" ] && { jhome="$p"; break; }
  done
fi
if [ -z "$jhome" ]; then                                    # Linux /usr/lib/jvm
  for d in /usr/lib/jvm/*21* /usr/lib/jvm/*17*; do
    [ -d "$d" ] && [ -x "$d/bin/javac" ] && { jhome="$d"; break; }
  done
fi
[ -n "$jhome" ] && emit_var JAVA_HOME "$jhome"

# --- Coursier app dir (metals, scala-cli) -- macOS and Linux locations -------
for d in "$HOME/Library/Application Support/Coursier/bin" \
         "$HOME/.local/share/coursier/bin"; do
  [ -d "$d" ] && emit_path "$d"
done

exit 0   # success even when the last probe (a missing dir) returned non-zero
