#!/bin/bash

HLP() {
    cat <<EOF
Usage: $0 [QCOW2_IMAGE] [-- EXTRA_QEMU_ARGS]

Launch a QEMU VM with predefined settings, allowing extra QEMU args after "--".

Default settings:
  - CPU: max
  - GPU: qxl
  - SMP: 2 cores
  - Memory: 4272MB
  - Filesystem: current directory shared as 'hostdir'
  - UEFI: /usr/share/OVMF/OVMF_CODE.fd

Example:
  $0 myvm.qcow2                          # Default settings
  $0 myvm.qcow2 -- -m 8G -smp 4          # Override RAM and CPU cores
  $0 myvm.qcow2 -- -vnc :1               # Enable VNC
EOF
    exit 0
}

# Show help if requested
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
    HLP
fi

# Check if image is provided
if [[ -z "$1" ]]; then
    echo "Error: No disk image specified" >&2
    HLP
    exit 1
fi

IMAGE="$(realpath "$1")"
shift  # Remove image path from arguments

# Split arguments into normal args and QEMU args (after --)
QEMU_EXTRA_ARGS=()
while [[ $# -gt 0 ]]; do
    if [[ "$1" == "--" ]]; then
        shift
        QEMU_EXTRA_ARGS=("$@")
        break
    else
        echo "Warning: Unknown argument '$1' (use '--' before QEMU args)" >&2
        shift
    fi
done

if [[ ! -f "$IMAGE" ]]; then
    echo "Error: Disk image not found: $IMAGE" >&2
    exit 1
fi

echo "Starting VM: $(basename "$IMAGE")"
if [[ ${#QEMU_EXTRA_ARGS[@]} -gt 0 ]]; then
    echo "Extra QEMU args: ${QEMU_EXTRA_ARGS[*]}"
fi

# Base QEMU command (hardcoded defaults)
qemu-system-x86_64 \
    -cpu max \
    -vga qxl \
    -smp 2 \
    -machine q35,accel=kvm:tcg \
    -name "$(basename "$IMAGE")" \
    -m 4272M \
    -rtc base=localtime \
    -virtfs local,path="$(pwd)",mount_tag=hostdir,security_model=mapped,id=hostdir \
    -boot c \
    -drive file="$IMAGE",format=qcow2,cache=none \
    -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE.fd \
    "${QEMU_EXTRA_ARGS[@]}"
