#!/usr/bin/env bash

# The script is created for starting a riscv64 qemu virtual machine with specific parameters.

RESTORE=$(echo -en '\001\033[0m\002')
YELLOW=$(echo -en '\001\033[00;33m\002')
RED=$(echo -en '\001\033[00;31m\002')

## Configuration
vcpu=8
memory=8
drive="openEuler-24.03SP2-V1-base-qemu-testing.qcow2"
fw="fw_payload_oe_uboot_2504.bin"
ssh_port=12055

check_qemu_version() {
    local version_output
    version_output=$(qemu-system-riscv64 --version 2>/dev/null)

    if [[ -z "$version_output" ]]; then
        echo "Error: qemu-system-riscv64 not found or failed to get version"
        return 1
    fi

    local version
    version=$(echo "$version_output" | grep -oE 'version [0-9]+\.[0-9]+\.[0-9]+' | awk '{print $2}')

    if [[ -z "$version" ]]; then
        echo "Error: Could not extract version number"
        return 1
    fi

    # Split version into components
    IFS='.' read -r major minor patch <<< "$version"

    # Check if version is outside recommended range (8.0.0 - 9.0.0)
    if (( major < 8 )) || (( major > 9 )) || (( major == 8 && minor == 0 && patch == 0 )) || (( major == 9 && minor == 0 && patch == 0 )); then
        echo "${RED}:: UNSUPPORTED QEMU VERSION: $version${RESTORE}"
        echo "${RED}:: The recommended QEMU version is 8.2.9${RESTORE}"
        return 1
    else
        echo "${YELLOW}:: NOTE: The recommended QEMU version is 8.2.9${RESTORE}"
        return 0
    fi
}

cmd="qemu-system-riscv64 \
  -nographic -machine virt \
  -smp "$vcpu" -m "$memory"G \
  -cpu max,sv48=on \
  -bios "$fw" \
  -drive file="$drive",format=qcow2,id=hd0,if=none \
  -object rng-random,filename=/dev/urandom,id=rng0 \
  -device virtio-vga \
  -device virtio-rng-device,rng=rng0 \
  -device virtio-blk-device,drive=hd0 \
  -device virtio-net-device,netdev=usernet \
  -netdev user,id=usernet,hostfwd=tcp::"$ssh_port"-:22 \
  -device qemu-xhci -usb -device usb-kbd -device usb-tablet"

echo ${YELLOW}:: Starting VM...${RESTORE}
echo ${YELLOW}:: Using following configuration${RESTORE}
echo ""
echo ${YELLOW}vCPU Cores: "$vcpu"${RESTORE}
echo ${YELLOW}Memory: "$memory"G${RESTORE}
echo ${YELLOW}Disk: "$drive"${RESTORE}
echo ${YELLOW}SSH Port: "$ssh_port"${RESTORE}
echo ""
echo ${YELLOW}:: NOTE: Make sure ONLY ONE .qcow2 file is${RESTORE}
echo ${YELLOW}in the current directory${RESTORE}
echo ""
echo ${YELLOW}:: Tip: Try setting DNS manually if QEMU user network doesn\'t work well. ${RESTORE}
echo ${YELLOW}:: HOWTO -\> https://serverfault.com/a/810639 ${RESTORE}
echo ""
echo ${YELLOW}:: Tip: If \'ping\' reports permission error, try reinstalling \'iputils\'. ${RESTORE}
echo ${YELLOW}:: HOWTO -\> \'sudo dnf reinstall iputils\' ${RESTORE}
echo ""

if check_qemu_version; then
    sleep 2
    eval $cmd
else
    exit 1
fi

