#!/bin/sh
# REPL test: start the REPL with scala-3 (no main class) on a dumb terminal,
# feed it lines one prompt at a time, and check the results, including a
# class from the -cp class path and the Debian message of :dep.
set -e

WORK="${AUTOPKGTEST_TMP:-$(mktemp -d)}"
cd "$WORK"
# The REPL keeps its history in user.home (from the password database, not
# $HOME).
export HOME="$WORK" TERM=dumb JAVA_OPTS="-Duser.home=$WORK"

mkdir lib
cat > Greeter.scala <<'X'
object Greeter:
  def hello(name: String): String = s"Hello, $name"
X
scalac-3 -d lib Greeter.scala

cat > lines.txt <<'X'
val x = 21 * 2
println(x)
println(Greeter.hello("Debian"))
:dep com.lihaoyi::os-lib:0.11.4
:quit
X

# Send a line only when the REPL shows its next prompt: the REPL reads
# ahead while it evaluates, so a fast pipe would lose lines.
rm -f in.fifo out.txt; mkfifo in.fifo
scala-3 -cp lib -color:never < in.fifo > out.txt 2>&1 &
pid=$!
exec 3> in.fifo
n=0
while IFS= read -r line; do
	n=$((n + 1)); t=0
	while [ "$(grep -o 'scala>' out.txt | wc -l)" -lt "$n" ]; do
		t=$((t + 1))
		if [ $t -gt 900 ]; then
			echo "timeout waiting for prompt $n" >&2; cat out.txt; kill $pid; exit 1
		fi
		sleep 0.2
	done
	printf '%s\n' "$line" >&3
done < lines.txt
exec 3>&-
wait $pid
cat out.txt

grep -qx 'scala> val x: Int = 42' out.txt
grep -qx 'scala> 42' out.txt
grep -qx 'scala> Hello, Debian' out.txt
grep -q 'downloading dependencies is not available in the Debian build' out.txt
if grep -q 'Exception' out.txt; then echo "unexpected exception" >&2; exit 1; fi
echo "repl test: PASS"
