prow-presubmit: make Prow only set --build_dir=. after v5.7

Prow tries to build Linux kernels in the source root directory. On newer
kernels, the best way to do this is to set the --build_dir flag to `.`.
Under the hood this sets the make variable `O=.` - on new kernels this
is fine, necessary, in fact. However, in kernels v5.2 and earlier Kbuild
doesn't know how to handle `O=.`. We only actually need to set the flag
in v5.7 kernels and later since KUnit defaulted to building in the
source root up until v5.7.

Signed-off-by: Brendan Higgins <brendanhiggins@google.com>
Change-Id: Ibb6ed5114014632ee7f701af83f14b69b7769050
diff --git a/kunit.sh b/kunit.sh
index a081019..c02c87c 100755
--- a/kunit.sh
+++ b/kunit.sh
@@ -33,6 +33,25 @@
 
 KUNIT_VERSION_ARGS=""
 
+KERNEL_VERSION_REGEX="([0-9]+)\.([0-9]+).*"
+
+if [[ $(make kernelversion) =~ $KERNEL_VERSION_REGEX ]]; then
+  MAJOR_VERSION="${BASH_REMATCH[1]}"
+  MINOR_VERSION="${BASH_REMATCH[2]}"
+  # --build_dir gets set to .kunit by default in v5.7, so we need to set it to
+  # the source root directory (.); otherwise, we can ignore it.
+  # In fact, we MUST omit --build_dir=. in v5.2 or earlier otherwise Kbuild will
+  # complain about an unclean tree:
+  # https://github.com/torvalds/linux/commit/25b146c5b8ceecd43c311552d325a4e403c639f2
+  if [[ $MAJOR_VERSION -gt 5 || ($MAJOR_VERSION -eq 5 && $MINOR_VERSION -ge 7) ]]; then
+    KUNIT_VERSION_ARGS="--build_dir=."
+  fi
+  echo "Linux kernel version: v${MAJOR_VERSION}.${MINOR_VERSION}"
+else
+  echo "WARNING: Not able to determine Linux kernel version!!!"
+  echo "Presubmit may report erroneous results!"
+fi
+
 # KUnit repos based on upstream have a default kunitconfig; we can check for
 # that to see if we are running a repo based on upstream or not.
 #
@@ -43,7 +62,6 @@
     cp ./arch/um/configs/kunit_defconfig .kunitconfig
   fi
   cp .kunitconfig .config
-  KUNIT_VERSION_ARGS="--build_dir=."
 else
   if [[ ! -f ./kunitconfig ]]; then
     cp /kunitconfig ./kunitconfig