#!/bin/sh
#
# RAUC qemu test runner script
#
# Executes the RAUC test suite in a safe qemu environment with simulated root
# privileges to emulate and test virtual devices such as block devices, NAND,
# etc.
#
# Usage:
#
# ./qemu-test <argument>
#
# Optional arguments:
#
#   coverage    Run with coverage report generation enabled
#   distcheck   Run distcheck make target
#   passthrough Enable passthrough of the host's CPU features
#   shell       Setup qemu test system and provide an interactive shell
#
# When no argument is given, the default test suite will be executed

set -e

rm -f qemu-test-ok

# TODO use virtfs with multidevs=remap on qemu 4.2
# https://github.com/qemu/qemu/commit/1a6ed33cc56997479bbe5b48337ff8da44585bd4

KERNEL_URL="https://github.com/jluebbe/linux/releases/download/rauc-test-20200908-1/bzImage"
KERNEL_SHA256SUM="6d12c543dc35deaa3b0946779cd88f258b6f2ad6b55775bba0bd04f52487d0e9"

check_kernel() {
  if test -f bzImage && echo "$KERNEL_SHA256SUM bzImage" | sha256sum --check --status; then
    return 0
  fi
  curl -L "$KERNEL_URL" -o bzImage.tmp
  if echo "$KERNEL_SHA256SUM bzImage.tmp" | sha256sum --check --status; then
    mv bzImage.tmp bzImage
  else
    echo "bad bzImage hash"
    return 1
  fi
}

check_kernel || exit 1

# make sure the tests are built
make TESTS= check > /dev/null

QEMU_ARGS=""
for x in "$@"; do
  if [ "$x" = "passthrough" ]; then
    QEMU_ARGS="$QEMU_ARGS -cpu host"
  fi
done

if test -w /dev/kvm; then
  QEMU_ARGS="$QEMU_ARGS -enable-kvm"
else
  echo "/dev/kvm is not accessible, using emulation"
fi

qemu-system-x86_64 \
  $QEMU_ARGS \
  -machine q35 \
  -m 512M \
  -smp 2 \
  -kernel bzImage \
  -nographic -serial mon:stdio \
  -no-reboot \
  -virtfs local,id=rootfs,path=/,security_model=none,mount_tag=/dev/root \
  -nic user,model=virtio-net-pci \
  -append "loglevel=6 console=ttyS0 nandsim.id_bytes=0x20,0xa2,0x00,0x15 nandsim.parts=0x100, root=/dev/root rootfstype=9p rw init=$(pwd)/qemu-test-init rauc.slot=system0 $*"

test -f qemu-test-ok
