#!/bin/bash
set -e -o pipefail

testimg=$1
arch=$(echo "$(basename -- "$(dirname -- "$testimg")")" | cut -d- -f2)

. debian/tests/qemu-cmd

workdir=$(mktemp -d)
trap "rm -rf $workdir" EXIT

QEMU_CMD+=(-netdev user,id=net0,tftp="$workdir",bootfile=__nonexistent__)
QEMU_CMD+=(-device vmxnet3,netdev=net0,id=net0,romfile=)

case "$testimg" in
    *.efi)
        mkfs.vfat -C --mbr=y "$workdir/test.img" 16384
        mcopy -i "$workdir/test.img" "$testimg" "::tests.efi"
        cat > "$workdir/startup.nsh" <<EOF
@echo -off
tests.efi
echo "IPXE_TEST_DONE"
reset -s
EOF
        mcopy -i "$workdir/test.img" "$workdir/startup.nsh" "::startup.nsh"
        ;;
    *.lkrn)
        # ljmp   $0xf000,$0xfff0
        echo "ea f0 ff 00 f0" | xxd -r -p > "$workdir/test.img"
        echo "55 aa" | xxd -r -p | dd of="$workdir/test.img" bs=1 seek=510 conv=notrunc
        truncate -s 1M "$workdir/test.img"
        QEMU_CMD+=(-kernel "$testimg" -no-reboot)
        ;;
    *)
        echo "Unsupported image type: $testimg" >&2
        exit 1
        ;;
esac

QEMU_CMD+=(-blockdev driver=raw,node-name=img,file.driver=file,file.filename="$workdir/test.img")
QEMU_CMD+=(-device virtio-scsi-pci,id=scsi -device scsi-hd,id=medium,bus=scsi.0,drive=img,bootindex=1)

expect -- - "${QEMU_CMD[@]}"<< 'EOF'
set timeout 120

proc abort {msg} {
  set ferr [open "/dev/fd/2" "w"]
  puts $ferr $msg
  close $ferr
  exit 1
}

spawn {*}$argv

expect {
    "*No bootable device"   {abort "Cannot Boot iPXE"}
    "*Shell>"               {abort "Cannot Boot iPXE"}
    eof                     {abort "VM terminates unexpectedly"}
    timeout                 {abort "Timeout"}
    -re {OK: all \d+ tests passed} {}
}

set timeout 10
expect {
    eof {}
    timeout {}
}
puts "\x1b\[!p"
exit 0
EOF
