#!/bin/sh
# Scala 3 program runner and REPL (Debian scala3). With a main class, runs a
# compiled program with the Scala 3 standard library on the class path;
# without one, starts the interactive shell (REPL) with that class path.
# Upstream's `scala` command is Scala CLI, which is not packaged: there is
# no script mode. JVM options can be given in JAVA_OPTS.
J=/usr/share/java
LIB=$J/scala-library-3.jar
# The REPL runs on the compiler, with JLine 4 (libjline4-java) as terminal.
REPLCP=$J/scala3-repl-3.jar:$J/scala3-directives-parser-3.jar
REPLCP=$REPLCP:$J/scala3-compiler-3.jar:$J/scala3-interfaces-3.jar:$J/tasty-core-3.jar:$LIB
REPLCP=$REPLCP:/usr/share/maven-repo/org/scala-lang/modules/scala-asm/debian/scala-asm-debian.jar
REPLCP=$REPLCP:$J/sbt-compiler-interface.jar
REPLCP=$REPLCP:$J/jline4-reader.jar:$J/jline4-terminal.jar:$J/jline4-terminal-jni.jar:$J/jline4-native.jar

usage() {
	echo "Usage: scala-3 [-cp|-classpath|--class-path PATH] MAINCLASS [ARGS...]" >&2
	echo "       scala-3 [-cp|-classpath|--class-path PATH] [COMPILER-OPTIONS...]" >&2
	echo "       scala-3 -version" >&2
	echo "Runs a program compiled with scalac-3, or starts the REPL when no main" >&2
	echo "class is given (default class path: .). No scripts, no Scala CLI." >&2
	exit "$1"
}

CP=.
REPL=no
while [ $# -gt 0 ]; do
	case "$1" in
	-cp|-classpath|--class-path)
		[ $# -ge 2 ] || usage 2
		CP=$2; shift 2 ;;
	-version|--version)
		exec java -cp "$LIB" scala.util.Properties ;;
	-h|-help|--help)
		usage 0 ;;
	--)
		shift; break ;;
	-*)
		# compiler options: for the REPL
		REPL=yes; break ;;
	*)
		break ;;
	esac
done
if [ $# -eq 0 ] || [ "$REPL" = yes ]; then
	# The JNI terminal provider of JLine loads a native library.
	# shellcheck disable=SC2086
	exec java $JAVA_OPTS --enable-native-access=ALL-UNNAMED -Dscala.usejavacp=true \
		-cp "$REPLCP" dotty.tools.repl.Main -usejavacp -classpath "$CP" "$@"
fi
# shellcheck disable=SC2086
exec java $JAVA_OPTS -cp "$CP:$LIB" "$@"
