#!/usr/bin/env bash
# Build the symbol-bearing interpreter reference used in the ELF experiment.
set -euo pipefail
cd "$(dirname "$0")/../.."

if [[ $# != 2 ]]; then
    printf 'usage: %s MODULE.bc NEW_OUTPUT_ELF\n' "$0" >&2
    exit 2
fi
: "${JAVA_HOME:?Set JAVA_HOME to GraalVM Community JDK 24.0.2}"
module=$(realpath -e "$1")
output=$(realpath -m "$2")
if [[ -e $output ]]; then
    printf 'output already exists: %s\n' "$output" >&2
    exit 1
fi
if [[ ! -f target/classes/dev/graalc/SqliteShell.class ||
      ! -f target/dependency/llvm-language-24.2.2.jar ]]; then
    printf 'build the pinned launcher and dependencies with make java-package first\n' >&2
    exit 1
fi

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/classes" "$work/src" "$(dirname "$output")"
cp -a target/classes/. "$work/classes/"
cp "$module" "$work/classes/dev/graalc/sqlite-api-shell.bc"
# The fallback engine has no JIT options. Keep the shell and guest module intact.
python3 - src/main/java/dev/graalc/LlvmRuntime.java "$work/src/LlvmRuntime.java" <<'PY'
from pathlib import Path
import sys

source, output = map(Path, sys.argv[1:])
java = source.read_text()
begin = java.index("        if (interpretOnly ||")
end = java.index("        if (!libraries.isEmpty())", begin)
output.write_text(java[:begin] + '        builder.option("engine.WarnInterpreterOnly", "false");\n'
                  + java[end:])
PY
classpath="$work/classes"
for jar in "$PWD"/target/dependency/*.jar; do
    if [[ ${jar##*/} != truffle-runtime-24.2.2.jar ]]; then
        classpath="$classpath:$jar"
    fi
done
"$JAVA_HOME/bin/javac" -cp "$classpath" -d "$work/classes" "$work/src/LlvmRuntime.java"
"$JAVA_HOME/bin/native-image" --no-fallback -Ob -march=compatibility --parallelism=2 -J-Xmx2000m \
    -J-Dtruffle.UseFallbackRuntime=true -H:+UnlockExperimentalVMOptions -H:-DeleteLocalSymbols \
    '-H:IncludeResources=dev/graalc/sqlite-api-shell\.bc' -H:-UnlockExperimentalVMOptions \
    -cp "$classpath" -o "$output" dev.graalc.SqliteShell
