#
# Handy functions used when parsing command line options
#

# Is the invoked interface (kvm-xfstests, gce-xfstests, etc.) in the given list?
flavor_in ()
{
    local flavor
    for flavor ; do
	if test "$XFSTESTS_FLAVOR" = "$flavor" ; then
	    return 0
	fi
    done
    return 1
}

find_kernel_to_use()
{
    local kernel_in_build

    case "$ARCH" in
        i386|amd64)
	    kernel_in_build=arch/x86/boot/bzImage
	    ;;
	arm64)
	    kernel_in_build=arch/arm64/boot/Image
	    ;;
	*)
	    echo "Unknown architecture in find_kernel_to_use: $ARCH"
	    exit 1
	    ;;
    esac

    if test -z "$OVERRIDE_KERNEL" ; then
	if test -x $KBUILD_DIR/kbuild &&
		$KBUILD_DIR/kbuild --get-kbuild-config >& /dev/null ; then
	    t=$($KBUILD_DIR/kbuild --get-build-dir --arch $ARCH)
	    if test -n "$t" -a "$KERNEL" != "$t" -a \
		    "$KERNEL" != "$t/linux-image.deb" -a \
		    "$KERNEL" != "$t/$kernel_in_build" ; then
		echo "Detected kbuild config; using $t for kernel"
		KERNEL=$t
		OVERRIDE_KERNEL=$t
		if test -z "$OVERRIDE_MODULES" ; then
		    MODULES=
		fi
	    fi
	elif test -f "./$kernel_in_build" ; then
	    t=$(pwd)
	    if test "$KERNEL" != "$t" -a "$KERNEL" != "$t/$kernel_in_build"
	    then
		echo "Current directory appears to be a kernel tree; using it"
		KERNEL=$t
		OVERRIDE_KERNEL=$t
		if test -z "$OVERRIDE_MODULES" ; then
		    MODULES=
		fi
	    fi
	fi
    fi
    if flavor_in gce && test -d "$KERNEL" -a -f "$KERNEL/linux-image.deb"
    then
	KERNEL="$KERNEL/linux-image.deb"
	MODULES=""
    fi
    if test -d "$KERNEL" ; then
	if test -z "$OVERRIDE_MODULES" -a -f "$KERNEL/modules.tar.xz" ; then
	    MODULES="$KERNEL/modules.tar.xz"
	fi
	KERNEL="$KERNEL/$kernel_in_build"
    fi
}
