#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd -- "$SCRIPT_DIR/.." && pwd)"
OUT_DIR="${1:-$REPO_ROOT/.local/tmp/tc-out}"
PORT="${PORT:-18080}"

if [[ ! -f "$OUT_DIR/vmlinuz64" || ! -f "$OUT_DIR/tinycore-sqlite-wasm.gz" ]]; then
  echo "Usage: $0 <image-dir containing vmlinuz64 and tinycore-sqlite-wasm.gz>" >&2
  exit 1
fi

exec qemu-system-x86_64 \
  -m 512M \
  -smp 2 \
  -nographic \
  -kernel "$OUT_DIR/vmlinuz64" \
  -initrd "$OUT_DIR/tinycore-sqlite-wasm.gz" \
  -append "console=ttyS0,115200 loglevel=3" \
  -netdev "user,id=net0,hostfwd=tcp:127.0.0.1:${PORT}-:8080" \
  -device virtio-net-pci,netdev=net0
