#!/bin/bash

# THIS SCRIPT IS USED TO RUN QEMU ARC EMULATOR DIRECTLY ON CI ONLY.
# USUALLY, you SHOULD NOT RUN IT ON YOUR LOCAL MACHINE.
# INSTEAD, YOU SHOULD USE `west build -t run` COMMAND.

# Two arguments. first is the path to the zephyr-sdk, second is the path to the zephyr elf.
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <path_to_zephyr_sdk> <path_to_zephyr_elf>"
    exit 1
fi

ZEPHYR_SDK_PATH=$1
ZEPHYR_ELF_PATH=$2

if [ ! -d "$ZEPHYR_SDK_PATH" ]; then
    echo "Error: Zephyr SDK path does not exist: $ZEPHYR_SDK_PATH"
    exit 1
fi
if [ ! -f "$ZEPHYR_ELF_PATH" ]; then
    echo "Error: Zephyr ELF file does not exist: $ZEPHYR_ELF_PATH"
    exit 1
fi

# this command is copied from the content of build.ninja which is generated by west build.
# please do not modify it unless synchronizing with the build.ninja file.
$ZEPHYR_SDK_PATH/sysroots/x86_64-pokysdk-linux/usr/bin/qemu-system-arc \
  -cpu arcem -m 8M \
  -nographic -no-reboot -monitor none \
  -global cpu.firq=false \
  -global cpu.num-irqlevels=15 \
  -global cpu.num-irq=25 \
  -global cpu.ext-irq=20 \
  -global cpu.freq_hz=10000000 \
  -global cpu.timer0=true \
  -global cpu.timer1=true \
  -global cpu.has-mpu=true \
  -global cpu.mpu-numreg=16 \
  -net none \
  -pidfile qemu.pid \
  -chardev stdio,id=con,mux=on \
  -serial chardev:con \
  -mon chardev=con,mode=readline \
  -icount shift=6,align=off,sleep=off \
  -rtc clock=vm \
  -kernel $ZEPHYR_ELF_PATH
