#!/bin/sh
# Execute root handoff and successive user-space yields with the production packages.
set -eu
emulator=${RAD_EMULATOR:-emulator}
harts=${1:-1 2 8}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM
cp kernel/kernel.rad "$work/kernel.rad"
printf '\nexport mod dispatchcheck;\n' >> "$work/kernel.rad"
mkdir "$work/kernel"
cp kernel/kernel/*.rad "$work/kernel/"
cp test/scheduling/kernel/dispatchcheck.rad "$work/kernel/"
sed -i '/let cause = trap::classify(frame.cause);/a\    super::dispatchcheck::observe(frame);' "$work/kernel/boot.rad"
sh test/acceptance/compile "$emulator" "$work"
cat test/scheduling/machine.ras kernel/kernel/*.ras > "$work/scheduling.ras"
"$emulator" -memory-size=385024 -data-size=348160 -stack-size=1024 -run bin/kernel.build.rv64 \
    -- "$work/std.ril" "$work/kernel.ril" "$work/scheduling.ras" "$work/scheduling.rv64" bin/root.ril bin/scheduler.ril
for count in $harts; do
    if [ "${KERNEL_REPLAY:-0}" = 1 ]; then
        sh test/acceptance/replay scheduling "$emulator" "$work/scheduling.rv64" "$count"
    else
    "$emulator" -machine -harts="$count" -memory-size=262144 -max-steps=2000000000 -run "$work/scheduling.rv64"
    fi
    printf 'scheduling: %s-hart root handoff, four user-space yields, and checked shutdown passed\n' "$count"
done
