#!/bin/sh
#
# Starts Stemma. Needs a Java 21 (or newer) runtime: JAVA_HOME if set, otherwise the "java" on the PATH.
#
#   bin/stemma [path/to/repository]
#
# Environment:
#   JAVA_HOME           Java installation to use
#   STEMMA_OPTS         extra options for the JVM, e.g. "-Xmx2g"
#   STEMMA_CONFIG_DIR   keep the settings somewhere else (default: the config folder of this installation)
#
# Stemma is portable: it keeps its settings and library in <installation>/config and writes nothing to the
# user's home directory or any other system location.

# Find the installation folder, also when this script is started through a symbolic link.
SCRIPT="$0"
while [ -h "$SCRIPT" ]; do
    LINK_TARGET=$(ls -ld -- "$SCRIPT" | sed 's/.* -> //')
    case "$LINK_TARGET" in
        /*) SCRIPT="$LINK_TARGET" ;;
        *)  SCRIPT="$(dirname -- "$SCRIPT")/$LINK_TARGET" ;;
    esac
done
APP_HOME=$(cd "$(dirname -- "$SCRIPT")/.." > /dev/null 2>&1 && pwd -P) || {
    echo "stemma: cannot determine the installation folder" >&2
    exit 1
}

# Find Java.
if [ -n "$JAVA_HOME" ] && [ -x "$JAVA_HOME/bin/java" ]; then
    JAVACMD="$JAVA_HOME/bin/java"
elif command -v java > /dev/null 2>&1; then
    JAVACMD=$(command -v java)
else
    echo "stemma: no Java found. Install a Java 21 runtime or set JAVA_HOME." >&2
    exit 1
fi

# Java 21 or newer?
JAVA_MAJOR=$("$JAVACMD" -version 2>&1 | sed -n 's/.*version "\([0-9][0-9]*\).*/\1/p' | head -n 1)
if [ -n "$JAVA_MAJOR" ] && [ "$JAVA_MAJOR" -lt 21 ]; then
    echo "stemma: Java $JAVA_MAJOR found at $JAVACMD, but Java 21 or newer is required." >&2
    exit 1
fi

# STEMMA_OPTS is meant to be split into several words.
# shellcheck disable=SC2086
exec "$JAVACMD" $STEMMA_OPTS -Dstemma.home="$APP_HOME" -cp "$APP_HOME/lib/*" \
    io.github.jbastgen.stemma.app.Launcher "$@"
