#!/usr/bin/env bash
# run-arje-qemu.sh — bootea el initrd de arje bajo qemu-system-x86_64.
#
# Uso:
#   scripts/run-arje-qemu.sh [initrd] [kernel]
#
# Defaults:
#   initrd  out/arje.initrd.cpio.gz
#   kernel  $(uname -r) o /boot/vmlinuz-* (primer match)
#
# Env:
#   QEMU         binario de qemu (default: qemu-system-x86_64)
#   KERNEL_CMD   extra cmdline kernel (se concatena al fijo)
#   MEM          RAM en MB (default: 1024)
#   SMP          CPUs virtuales (default: 2)
#   ACCEL        kvm|tcg (default: kvm si /dev/kvm existe)
#   HEADLESS     1 → sin display (consola en stdio)
#
# El initrd contiene su propio /init → ente-zero corre como PID 1 real.

set -euo pipefail

INITRD="${1:-out/arje.initrd.cpio.gz}"
KERNEL="${2:-}"
QEMU="${QEMU:-qemu-system-x86_64}"
MEM="${MEM:-1024}"
SMP="${SMP:-2}"
KERNEL_CMD="${KERNEL_CMD:-}"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$REPO_DIR"

if [ ! -f "$INITRD" ]; then
  echo "[run-qemu] initrd no encontrado: $INITRD" >&2
  echo "         Generalo primero con: scripts/build-arje-initrd.sh" >&2
  exit 2
fi

if [ -z "$KERNEL" ]; then
  # En orden: /boot/vmlinuz-$(uname -r), primer vmlinuz-*, /boot/bzImage.
  for cand in "/boot/vmlinuz-$(uname -r)" /boot/vmlinuz-* /boot/bzImage*; do
    if [ -f "$cand" ]; then KERNEL="$cand"; break; fi
  done
fi

if [ -z "$KERNEL" ] || [ ! -f "$KERNEL" ]; then
  echo "[run-qemu] kernel no encontrado." >&2
  echo "         Pasalo como 2do arg o instalá linux-image-amd64." >&2
  echo "         También podés bajar uno: " >&2
  echo "           wget https://kernel.ubuntu.com/...vmlinuz" >&2
  exit 3
fi

# KVM si está disponible.
ACCEL="${ACCEL:-}"
if [ -z "$ACCEL" ]; then
  if [ -e /dev/kvm ] && [ -r /dev/kvm ] && [ -w /dev/kvm ]; then
    ACCEL="kvm"
  else
    ACCEL="tcg"
  fi
fi

DISPLAY_ARGS=()
if [ "${HEADLESS:-0}" = "1" ]; then
  DISPLAY_ARGS+=( -nographic -serial mon:stdio )
  KERNEL_CMD="console=ttyS0,115200 $KERNEL_CMD"
else
  DISPLAY_ARGS+=( -nographic -serial mon:stdio )
  KERNEL_CMD="console=ttyS0,115200 $KERNEL_CMD"
fi

CMDLINE="rdinit=/init panic=10 loglevel=4 $KERNEL_CMD"

echo "[run-qemu] kernel: $KERNEL"
echo "[run-qemu] initrd: $INITRD ($(du -h "$INITRD" | cut -f1))"
echo "[run-qemu] accel:  $ACCEL"
echo "[run-qemu] mem:    ${MEM}M, smp: $SMP"
echo "[run-qemu] cmdline: $CMDLINE"
echo "[run-qemu] (Ctrl-A X en stdio mode para salir)"

exec "$QEMU" \
  -accel "$ACCEL" \
  -m "$MEM" -smp "$SMP" \
  -kernel "$KERNEL" \
  -initrd "$INITRD" \
  -append "$CMDLINE" \
  "${DISPLAY_ARGS[@]}" \
  -no-reboot
