#!/bin/sh

# Kotlin compile wrapper-script for 'compile.sh'.
# See that script for syntax and more info.
#
# This script byte-compiles with the kotlinc compiler and
# generates a shell script to run it with the java interpreter with Kotlin
# libraries later.
#
# This script requires that kotlinc is installed in the chroot.

DEST="$1" ; shift
MEMLIMIT="$1" ; shift
MAINSOURCE="$1"
MAINCLASS=""
COMPILESCRIPTDIR="$(dirname "$0")"

# Replace this with the directory where kotlinc is located if it is not in your path.
# Note that you then also might want to fix this in the compiler and runner version commands.
# For example
# KOTLIN_DIR=/usr/lib/kotlinc/bin
KOTLIN_DIR="$(dirname "$(realpath "$(command -v kotlinc)")")"

# Stack size in the JVM in KB. Note that this will be deducted from
# the total memory made available for the heap.
MEMSTACK=65536

# Amount of memory reserved for the Java virtual machine in KB. The
# default below is just above the maximum memory usage of current
# versions of the jvm, but might need increasing in some cases.
MEMJVM=65536

MEMRESERVED=$((MEMSTACK + MEMJVM))

# Calculate Kotlin program memlimit as MEMLIMIT - max. JVM memory usage:
MEMLIMITJAVA=$((MEMLIMIT - MEMRESERVED))

if [ $MEMLIMITJAVA -le 0 ]; then
	echo "internal-error: total memory $MEMLIMIT KiB <= $MEMJVM + $MEMSTACK = $MEMRESERVED KiB reserved for JVM and stack leaves none for heap."
	exit 1
fi

# Allow overriding Kotlin main class (should not be necessary):
if [ -z "$ENTRY_POINT" ]; then
	[ -n "$DEBUG" ] && echo "Debug: no ENTRY_POINT provided, trying to detect main class."
else
	[ -n "$DEBUG" ] && echo "Debug: using main class provided by ENTRY_POINT='$ENTRY_POINT'."
	MAINCLASS="$ENTRY_POINT"
fi

# Byte-compile:
# Adding -Djava.io.tmpdir=/ here to avoid the compiler from crashing.
# As part of the preloader of the kotlin compiler, the value of this property
# gets copied into the idea.home.path property here:
# https://github.com/JetBrains/kotlin/blob/8a0969156f86b7d1ae09ce140794ff554109c25f/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/compat.kt#L23
# Then in the actual compiler, the value of the property gets checked whether it is a directory:
# https://github.com/JetBrains/intellij-community/blob/f36a688bd8541b7302246ea4f4b8f76b2223d2d7/platform/util/src/com/intellij/openapi/application/PathManager.java#L88
# Typically, java.io.tmpdir is a /tmp which doesn't exist in our chroot so the
# check fails. When passing in / as java.io.tmpdir, kotlinc is happy, although
# the dir is not writable.
"${KOTLIN_DIR}"/kotlinc -d . -Djava.io.tmpdir=/ "$@"
EXITCODE=$?
[ "$EXITCODE" -ne 0 ] && exit $EXITCODE

KOTLIN_STDLIB="$(dirname "$KOTLIN_DIR")/lib/kotlin-stdlib.jar"

if [ -z "$MAINCLASS" ]; then
	# Look for class that has the 'main' function:
	CLASSNAMES="$(find ./* -type f -regex '^.*\.class$' \
	            | sed -e 's/\.class$//' -e 's/^\.\///' -e 's/\//./g')"
	MAINCLASS=$(java -cp "$COMPILESCRIPTDIR:$KOTLIN_STDLIB" DetectMain "$(pwd)" $CLASSNAMES)
	EXITCODE=$?

	# Report the entry point, so it can be saved, e.g. for later replay:
	echo "Info: detected entry_point: $MAINCLASS"

	[ "$EXITCODE" -ne 0 ] && exit $EXITCODE
else
	# Check if entry point is valid
	java -cp "$COMPILESCRIPTDIR:$KOTLIN_STDLIB" DetectMain "$(pwd)" $MAINCLASS > /dev/null
	EXITCODE=$?
	[ "$EXITCODE" -ne 0 ] && exit $EXITCODE
fi

# Write executing script:
# Executes java byte-code interpreter with following options (prefixed
# with -J to pass from kotlin to java):
# -Xmx: maximum size of memory allocation pool
# -Xms: initial size of memory, improves runtime stability
# -XX:+UseSerialGC: Serialized garbage collector improves runtime stability
# -Xss${MEMSTACK}k: stack size as configured abve
# -Dfile.encoding=UTF-8: set file encoding to UTF-8
cat > "$DEST" <<EOF
#!/bin/sh
# Generated shell-script to execute java interpreter on source.

# Detect dirname and change dir to prevent class not found errors.
if [ "\${0%/*}" != "\$0" ]; then
	cd "\${0%/*}"
fi

# Add -J-DONLINE_JUDGE or -J-DDOMJUDGE below if you want it make easier for
# teams to do local debugging.

exec "${KOTLIN_DIR}"/kotlin -Dfile.encoding=UTF-8 -J-XX:+UseSerialGC -J-Xss${MEMSTACK}k -J-Xms${MEMLIMITJAVA}k -J-Xmx${MEMLIMITJAVA}k '$MAINCLASS' "\$@"
EOF

chmod a+x "$DEST"

exit 0
