#!/usr/bin/env bash
# Build + link + run CoreMark under MAME.
#
# Usage:
#   bash tests/coremark/runCoreMark.sh            # default: ITERATIONS=1
#   ITERATIONS=5 bash tests/coremark/runCoreMark.sh
#   bash tests/coremark/runCoreMark.sh --layer2

set -eu
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
CM_OBJ="$SCRIPT_DIR/build"
RT="$PROJECT_ROOT/runtime"

cd "$SCRIPT_DIR"
rm -rf "$CM_OBJ"
bash "$SCRIPT_DIR/build.sh" "$@"

# Link. CoreMark is ~50KB compiled; should fit single bank.
"$PROJECT_ROOT/tools/link816" -o coreMark.bin --text-base 0x1000 \
    "$RT/crt0.o" \
    "$RT/libc.o" "$RT/libgcc.o" "$RT/softFloat.o" "$RT/softDouble.o" \
    "$RT/math.o" "$RT/strtol.o" "$RT/snprintf.o" \
    "$RT/qsort.o" "$RT/timeExt.o" "$RT/extras.o" \
    $CM_OBJ/*.o

ls -la coreMark.bin
echo ""

# 0xC0DE sentinel = success; otherwise 0xBEEF = mid-run hang.
# Elapsed ticks at 0x025002..0x025005 (low/hi).
MAME_CHECK_FRAME=900 MAME_SECS=30 MAME_TIMEOUT=300 \
    bash "$PROJECT_ROOT/scripts/runInMame.sh" \
        "$SCRIPT_DIR/coreMark.bin" \
        --check 0x025000=c0de
