#!/usr/bin/env bash
#
# Prism launcher for Linux.
#
# Finds a Java runtime, then hands over. Kept as a script rather than a native
# launcher because the app is a single portable jar and the only thing that
# actually varies between distributions is where the JRE lives.

set -u

here="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
jar="$here/prism-desktop-all.jar"

if [ ! -f "$jar" ]; then
    echo "prism: cannot find $jar" >&2
    exit 1
fi

if [ -n "${JAVA_HOME:-}" ] && [ -x "$JAVA_HOME/bin/java" ]; then
    java="$JAVA_HOME/bin/java"
elif command -v java >/dev/null 2>&1; then
    java="java"
else
    cat >&2 <<'EOF'
PrismShare: no Java runtime found.

PrismShare needs Java 17 or newer:

    sudo apt install default-jre        # Debian, Ubuntu, Mint
    sudo dnf install java-latest-openjdk # Fedora
    sudo pacman -S jre-openjdk           # Arch

EOF
    exit 1
fi

version="$("$java" -version 2>&1 | head -1 | sed -E 's/.*"([0-9]+).*/\1/')"
case "$version" in
    ''|*[!0-9]*) ;;   # unreadable, let it try anyway
    *) if [ "$version" -lt 17 ]; then
           echo "prism: found Java $version, but 17 or newer is needed." >&2
           exit 1
       fi ;;
esac

exec "$java" -jar "$jar" "$@"
