#!/bin/bash

KERNELS_DIR=`realpath tmp_kernels`
CURR_ARCH=`uname -m`
ERRORS=()

list_kernels() {
        git --git-dir "$KERNELS_DIR/.git" branch -r | sed -e 's|origin/||' | grep -E 'aarch64|x86_64' | cut -c 3-
}

run_test() {
	local output rc
	name="$1"
	shift

	output=`"$@" 2>&1`
	rc=$?
	if [ $rc -eq 0 ]; then
		return
	fi
	echo "$0: [$name]: Command failed: $*"
	echo "$output"
	ERRORS+=("$name")
	return $rc
}

if ! run_test autogen ./autogen.sh; then
	echo "$0: autogen failed. Test setup broken"
	exit 2
fi
if ! run_test "configure" ./configure --disable-kernel-module; then
	echo "$0: configure failed. Test setup broken"
	exit 3
fi


njobs=`nproc || echo 1`
for kernel in `list_kernels`; do
	kver="${kernel#*/}"
	arch="${kernel%/*}"
	karch="$arch"
	case "$arch" in
	aarch64) karch="arm64";;
	esac
	(
		cd "$KERNELS_DIR"
		git switch -q "$arch/$kver"
	)
	export KSRC="$KERNELS_DIR"
	if [ "$arch" != "$CURR_ARCH" ]; then
		export ARCH="$karch"
		export export CROSS_COMPILE="${arch}-linux-gnu-"
	else
		export -n ARCH CROSS_COMPILE
	fi
	if ! run_test "config-$kernel" ./kernel/config_kernel; then
		continue
	fi
	if run_test "build-$kernel" make -C $PWD/kernel KSRC="$KSRC" KERNEL_PATH="$KSRC" -j$njobs; then
		echo "$0: $kernel: Success"
	fi
done

if [ ${#ERRORS[@]} -eq 0 ]; then
	exit 0
fi

echo "$0: Errors found in test:"
for e in ${ERRORS[@]}; do
	echo "   $e"
done
exit 1

