#!/bin/bash

set -eux

while [ $# -gt 0 ]; do
        case $1 in
        kernel=*)  KERNEL="${1#kernel=}"   ;;
        initrd=*)  INITRD="${1#initrd=}"   ;;
        image=*)   IMAGE="${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

timeout --foreground 10m \
        "$qemu" "${archopts[@]}" -m 512m \
        -kernel "$KERNEL" -initrd "$INITRD" \
        -append "$CMDLINE" \
        -drive file="$IMAGE",format=raw \
        -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 '^--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
