#!/bin/sh
# Preempt and resume U-mode and M-mode work through production dispatch.
set -eu
emulator=${RAD_EMULATOR:-emulator}
fixture=${1:-dispatch}
harts=${2:-1}
irq=${3:-0}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM
mkdir "$work/spin"
cp "test/$fixture/spin.rad" "$work/spin.rad"
cp kernel/kernel/abi.rad kernel/kernel/sys.rad "$work/spin/"
set -- -pkg spin -mod "$work/spin.rad" -mod "$work/spin/abi.rad" -mod "$work/spin/sys.rad"
if [ "$fixture" = mmio ]; then
    cp kernel/mmio.rad "$work/spin/"
    set -- "$@" -mod "$work/spin/mmio.rad"
fi
"$emulator" -memory-size=385024 -data-size=348160 -stack-size=1024 -run bin/radiance.rv64.dev \
    "$@" -entry spin -ril "$work"
cp kernel/kernel.rad "$work/kernel.rad"
printf '\nexport mod dispatchinput;\nexport mod dispatchcheck;\n' >> "$work/kernel.rad"
mkdir "$work/kernel"
cp kernel/kernel/*.rad "$work/kernel/"
for source in "test/$fixture"/kernel/*.rad; do
    cp "$source" "$work/kernel/"
    module=${source##*/}
    module=${module%.rad}
    if [ "$module" != dispatchcheck ]; then
        printf '\nexport mod %s;\n' "$module" >> "$work/kernel.rad"
    fi
done
length=$(wc -c < "$work/spin.ril")
printf '//! Binary user loop.\n/// Complete trusted input package.\nexport static INPUT: [u8; %s] = [\n' "$length" > "$work/kernel/dispatchinput.rad"
od -An -v -tu1 "$work/spin.ril" | awk '{ for (i = 1; i <= NF; i++) printf "%s,", $i; print "" }' >> "$work/kernel/dispatchinput.rad"
printf '];\n' >> "$work/kernel/dispatchinput.rad"
sh test/acceptance/compile "$emulator" "$work"
cat "test/$fixture/machine.ras" kernel/kernel/*.ras > "$work/dispatch.ras"
"$emulator" -memory-size=385024 -data-size=348160 -stack-size=1024 -run bin/kernel.build.rv64 \
    -- "$work/std.ril" "$work/kernel.ril" "$work/dispatch.ras" "$work/dispatch.rv64"
set --
if [ "$irq" -ne 0 ]; then set -- "-irq=$irq" "-irq-at=1"; fi
for count in $harts; do
    if [ "${KERNEL_REPLAY:-0}" = 1 ]; then
        sh test/acceptance/replay "$fixture" "$emulator" "$work/dispatch.rv64" "$count" "$@"
    else
    "$emulator" -machine -harts="$count" -memory-size=262144 -max-steps=2000000000 "$@" -run "$work/dispatch.rv64"
    fi
    printf '%s: %s-hart execution passed\n' "$fixture" "$count"
done
