#!/bin/bash

set -eux

while [ $# -gt 0 ]; do
        case $1 in
        kernel=*)  KERNEL="${1#kernel=}" ;;
        initrd=*)  INITRD="${1#initrd=}" ;;
        image=*)   IMAGES="${IMAGES+${IMAGES} }${1#image=}" ;;
        cmdline=*) CMDLINE="${1#cmdline=}" ;;
        output=*)  OUTPUT="${1#output=}" ;;
        esac
        shift
done

archopts=()

case $(uname -m) in
i?86)
        qemu="qemu-system-i386"
        ;;
ppc64*)
        qemu="qemu-system-ppc64"
        archopts=( -machine "pseries,usb=off" )
        ;;
aarch64)
        qemu="qemu-system-aarch64"
        archopts=( -machine "virt" )
        ;;
*)
        qemu=qemu-system-$(uname -m)
esac

devices=
id=0
for IMG in $IMAGES; do
    devices="${devices} -drive if=none,file=$IMG,format=raw,id=stick$id -device usb-storage,bus=xhci.0,drive=stick$id"
    id=$((id+1))
done

timeout --foreground 10m \
        "$qemu" "${archopts[@]}" -m 1024m \
        -kernel "$KERNEL" -initrd "$INITRD" \
        -append "$CMDLINE" \
        -device nec-usb-xhci,id=xhci $devices \
        -nographic -monitor none | tr -d '\r' | tee qemu-output.txt

rm -rf $OUTPUT
mkdir $OUTPUT
set -x
# Parse the output of qemu for things marked up by the "o" shell
# function in /sbin/init.
grep -e '^--FILE .* FILE--$' qemu-output.txt |
    while read LINE; do
        filename=$(echo $LINE | sed -e 's/--FILE \(.*\) FILE--.*/\1/')
        touch "$OUTPUT/$filename"
    done
grep -e '^--OUT .* BEGIN-- .* --END--$' qemu-output.txt |
    while read LINE; do
        filename=$(echo $LINE | sed -e 's/--OUT \(.*\) BEGIN--.*/\1/')
        content=$(echo $LINE | sed -e 's/--OUT .* BEGIN-- \(.*\) --END--/\1/')
        echo >> "$OUTPUT/$filename" "$content"
    done
