#!/usr/bin/env bash
set -euo pipefail

if [[ $# != 5 ]]; then
    printf 'Usage: %s PROJECT BRANCH_ELF COMBINED_ELF NATIVE_SHELL OUTPUT_DIRECTORY\n' "$0" >&2
    exit 2
fi

project=$(realpath -e "$1")
branches=$(realpath -e "$2")
combined=$(realpath -e "$3")
native=$(realpath -e "$4")
out=$(realpath -m "$5")
mkdir "$out"

"$project/scripts/check-binary-parity" "$combined" --original "$branches" \
    --native "$native" --lookups 256 | tee "$out/shell-parity.txt"
{
    printf '%s\n' 'exec CREATE TABLE kv(id INTEGER PRIMARY KEY, value INTEGER NOT NULL); INSERT INTO kv VALUES (1,-9223372036854775808),(2,9223372036854775807);'
    printf '%s\n' 'prepare SELECT value FROM kv WHERE id = ?1;'
    for ((iteration = 0; iteration < 256; ++iteration)); do
        printf '%s\n' 'bind-int 1 1' step step reset 'bind-int 1 2' step step reset 'bind-int 1 3' step reset
    done
    printf '%s\n' finalize
} > "$out/lookup.sql"
LC_ALL=C TZ=UTC "$native" :memory: < "$out/lookup.sql" > "$out/native.stdout"
LC_ALL=C TZ=UTC CGRAAL_INTERPRET=1 "$combined" :memory: \
    < "$out/lookup.sql" > "$out/interpreter.stdout" 2> "$out/interpreter.stderr"
LC_ALL=C TZ=UTC CGRAAL_TRACE=1 CGRAAL_INTERPRET=0 "$combined" -Xmx896m \
    -Dpolyglot.compiler.MaximumGraalGraphSize=150000 \
    -Dpolyglot.engine.BackgroundCompilation=false \
    -Dpolyglot.engine.CompileOnly=sqlite3VdbeExecLookup \
    -Dpolyglot.engine.CompileImmediately=true :memory: \
    < "$out/lookup.sql" > "$out/jit.stdout" 2> "$out/jit.trace"
cmp "$out/native.stdout" "$out/interpreter.stdout"
cmp "$out/native.stdout" "$out/jit.stdout"
grep -E 'opt done.* sqlite3VdbeExecLookup +\|Tier 2\|' "$out/jit.trace" > "$out/jit-installed.txt"
sha256sum "$combined" "$out/lookup.sql" "$out/"{native,interpreter,jit}.stdout > "$out/verification.sha256"
cat "$out/jit-installed.txt"
