#!/bin/sh
# Resolve and execute references beyond module index 127.
set -eu
emulator=${RAD_EMULATOR:-emulator}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM
mkdir "$work/capacity"
set -- -pkg capacity -mod "$work/capacity.rad"
index=0
while [ "$index" -lt 127 ]; do
    printf 'export mod m%s;\n' "$index" >> "$work/capacity.rad"
    printf '/// Return this module index.\nexport fn value() -> u64 { return %s; }\n' "$index" > "$work/capacity/m$index.rad"
    set -- "$@" -mod "$work/capacity/m$index.rad"
    index=$((index + 1))
done
printf 'use capacity::m126;\n/// Check a package root beyond module index 127.\n@default fn main() -> u64 { assert m126::value() == 126; return 0; }\n' > "$work/entry.rad"
set -- "$@" -pkg entry -mod "$work/entry.rad"
"$emulator" -memory-size=385024 -data-size=348160 -stack-size=1024 \
    -run bin/radiance.rv64.dev "$@" -entry entry -o "$work/capacity.rv64"
"$emulator" -run "$work/capacity.rv64"
printf 'module scopes: references beyond index 127 passed\n'
