#!/usr/bin/env bash
# Check which virtualization technology to use
# We prefer kvm, kqemu, userspace in that order.
set -eu

export PATH=/usr/sbin:/usr/bin:/sbin:/bin
ARCH="${ARCH-$(uname -m)}"
QEMU_CPU="${QEMU_CPU:-max}"

quote_args() {
    local arg args=()
    for arg in "$@"; do
        if [[ -z $arg || $arg =~ [[:space:]\'] ]]; then
            args+=("'${arg//\'/\'\\\'\'}'")
        else
            args+=("$arg")
        fi
    done
    echo "${args[*]}"
}

set_vmlinux_env() {
    if [[ ${KVERSION-} ]]; then
        VMLINUZ=${VMLINUZ-"/lib/modules/${KVERSION}/vmlinuz"}
        if ! [ -f "$VMLINUZ" ]; then
            VMLINUZ="/lib/modules/${KVERSION}/vmlinux"
        fi

        if ! [ -f "$VMLINUZ" ]; then
            VMLINUZ="/lib/modules/${KVERSION}/Image"
        fi

        if ! [ -f "$VMLINUZ" ]; then
            [[ -f /etc/machine-id ]] && read -r MACHINE_ID < /etc/machine-id

            if [[ ${MACHINE_ID-} ]] && { [[ -d /boot/${MACHINE_ID} ]] || [[ -L /boot/${MACHINE_ID} ]]; }; then
                VMLINUZ="/boot/${MACHINE_ID}/$KVERSION/linux"
            elif [ -f "/boot/vmlinuz-${KVERSION}" ]; then
                VMLINUZ="/boot/vmlinuz-${KVERSION}"
            elif [ -f "/boot/vmlinux-${KVERSION}" ]; then
                VMLINUZ="/boot/vmlinux-${KVERSION}"
            elif [ -f "/boot/kernel-${KVERSION}" ]; then
                VMLINUZ="/boot/kernel-${KVERSION}"
            elif [ -f "/boot/Image-${KVERSION}" ]; then
                VMLINUZ="/boot/Image-${KVERSION}"
            fi
        fi
    fi

    ! [ -f "${VMLINUZ-}" ] && VMLINUZ=$(find /boot/vmlinuz-* -type f 2> /dev/null | tail -1)
    ! [ -f "${VMLINUZ-}" ] && VMLINUZ=$(find /lib/modules/ -type f -name vmlinuz 2> /dev/null | tail -1)
    ! [ -f "${VMLINUZ-}" ] && VMLINUZ=$(find /lib/modules/ -type f -name Image 2> /dev/null | tail -1)

    if ! [ -f "$VMLINUZ" ]; then
        echo "Could not find a Linux kernel version to test with!" >&2
        echo "Please install linux." >&2
        exit 1
    fi
}

[[ -x /usr/bin/qemu ]] && BIN=/usr/bin/qemu && ARGS=(-cpu "$QEMU_CPU")
(lsmod | grep -q '^kqemu ') && BIN=/usr/bin/qemu && ARGS=(-kernel-kqemu -cpu host)
[[ -z ${NO_KVM-} && -c /dev/kvm && -x /usr/bin/kvm ]] && BIN=/usr/bin/kvm && ARGS=(-cpu host)
[[ -z ${NO_KVM-} && -c /dev/kvm && -x /usr/bin/qemu-kvm ]] && BIN=/usr/bin/qemu-kvm && ARGS=(-cpu host)
[[ -z ${NO_KVM-} && -c /dev/kvm && -x /usr/libexec/qemu-kvm ]] && BIN=/usr/libexec/qemu-kvm && ARGS=(-cpu host)
[[ -x "/usr/bin/qemu-system-${ARCH}" ]] && BIN="/usr/bin/qemu-system-${ARCH}" && ARGS=(-cpu "$QEMU_CPU")
[[ -z ${NO_KVM-} && -c /dev/kvm && -x "/usr/bin/qemu-system-${ARCH}" ]] && BIN="/usr/bin/qemu-system-${ARCH}" && ARGS=(-enable-kvm -cpu host)

[[ ${BIN-} ]] || {
    echo "Could not find a working KVM or QEMU to test with!" >&2
    echo "Please install kvm or qemu." >&2
    exit 1
}

if test "${1-}" = "--supports"; then
    option="$2"
    "$BIN" -help | grep -q "^$option"
    exit 0
fi

case "$ARCH" in
    aarch64 | arm64)
        ARGS+=(-M "virt,gic-version=max")
        ;;
    amd64 | i?86 | x86_64)
        ARGS+=(-M q35)
        ;;
    arm | armhf | armv7l)
        ARGS+=(-M virt)
        ;;
    ppc64el | ppc64le)
        ARGS+=(-M "cap-ccf-assist=off,cap-cfpc=broken,cap-ibs=broken,cap-sbbc=broken")
        ;;
esac

# Provide rng device sourcing the hosts /dev/urandom and other standard parameters
ARGS+=(-smp 2 -m "${MEMORY-1024}" -nodefaults -vga none -display none -no-reboot -watchdog-action poweroff -device virtio-rng-pci)

if ! [[ $* == *-daemonize* ]] && ! [[ $* == *-daemonize* ]]; then
    ARGS+=(-serial stdio)
fi

# virtual hardware watchdog not available on s390x
if [[ $ARCH != "s390x" ]]; then
    ARGS+=(-device i6300esb)
fi

# only set -kernel if -initrd is specified
if [[ $* == *-initrd* ]]; then
    for arg in "$@"; do
        [[ $1 == *-initrd* ]] && break
    done

    KVERSION=$(lsinitrd "$arg" | grep modules.dep | head -1 | rev | cut -d'/' -f2 | rev)
    set_vmlinux_env
    ARGS+=(-kernel "$VMLINUZ")
fi

echo "${0##*/}: $BIN $(quote_args "${ARGS[@]}") $(quote_args "$@")"
exec "$BIN" "${ARGS[@]}" "$@"
