#!/bin/bash

# Script originally written by zxq5, I added separate scripts to remove `jq` dependency.

script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)

source $script_dir/build.sh

# Error handling
set -e
trap 'echo -e "${RED}${BOLD}error${NC}: build failed" >&2' ERR

echo -e "${GREEN}${BOLD} Running kernel in release mode."


if [ $VM_MEMORY ]; then
    vm_memory_flag="-m $VM_MEMORY"
else
    vm_memory_flag="-m 2G"
fi

# Check if KVM is available
if [ "${KVM_FLAG:-enable}" = "disable" ]; then
    warning "KVM acceleration disabled by user"
    kvm_flag=""
elif [ -c "/dev/kvm" ] && [ -w "/dev/kvm" ]; then
    info "KVM acceleration enabled"
    kvm_flag="-enable-kvm"
else
    warning "KVM acceleration not available (is kvm module loaded?)"
    kvm_flag=""
fi

if [ $USE_LEGACY_BIOS ]; then
    boot_flags=""
else
#   Check for the presence of the OVMF firmware.
    if [ ! -f $build_dir/RELEASEX64_OVMF_CODE.fd ]; then
        info "Downloading OVMF UEFI firmware for QEMU"
        info "To disable this, set USE_LEGACY_BIOS=1."
        pushd $build_dir
        curl https://retrage.github.io/edk2-nightly/bin/RELEASEX64_OVMF_CODE.fd -LO || error "failed to download OVMF firmware for UEFI"
        curl https://retrage.github.io/edk2-nightly/bin/RELEASEX64_OVMF_VARS.fd -LO || error "failed to download OVMF firmware for UEFI"
        popd
    fi

    boot_flags="-drive if=pflash,format=raw,readonly=on,file=$build_dir/RELEASEX64_OVMF_CODE.fd \
                -drive if=pflash,format=raw,file=$build_dir/RELEASEX64_OVMF_VARS.fd"
fi

cd "$project_root"
qemu-system-x86_64 -M q35 \
    ${kvm_flag} \
    -cdrom "$build_dir/image.iso" \
    -boot d \
    ${vm_memory_flag} \
    ${serial_flags} \
    -no-reboot \
    ${boot_flags}

