#!/bin/bash

set -euo pipefail

KVER=$1
KDIR=$2
STAGE=$3

if [ -z "$KVER" ] || [ ! -d "$KDIR" ] || [ -z "$STAGE" ]; then
	echo "Usage: $0 <kernel_ver> <kernel_dir> <stage>"
	exit 1
fi

OFA_DIR="$PWD/mlnx-ofed-kernel"
NPROC="$(nproc)"

configure_mlnx_ofed_kernel(){
	rm -rf source || true
	mkdir -p source || exit 2
	ls -1 | grep -v source | xargs -iELEM cp ELEM -r source || exit 2
	find compat -type f -exec touch -t 200012201010 '{}' \; || true

	# Use default configuration from ../mlnx-ofed-kernel/ofed_scripts/dkms_ofed
	./configure --with-njobs="$NPROC" --kernel-version="$KVER" --kernel-sources="$KDIR" \
		--with-core-mod \
		--with-user_mad-mod \
		--with-user_access-mod \
		--with-addr_trans-mod \
		--with-mlx5-mod \
		--with-mlxfw-mod \
		--with-ipoib-mod \
		|| exit 2
}

build_mlnx_ofed_kernel() {
	make distclean || true
	make -j"$NPROC" || exit 2
}


configure_knem() {
	find . -type f -exec touch -t 200012201010 '{}' \; || true
	./autogen.sh || exit 2

	# need pkgconf, see https://stackoverflow.com/questions/8578181/using-the-pkg-config-macro-pkg-check-modules-failing
	./configure --with-njobs="$NPROC" --with-linux-release="$KVER" --with-linux="$KDIR" --with-linux-build="$KDIR" || exit 2
}

build_knem() {
	make -j"$NPROC" || exit 2
}

build_generic_dkms() {
	make clean || true
	make -j"$NPROC" KVER="$KVER" K_BUILD="$KDIR" "$@"
}

build_generic_dkms_ofa() {
	build_generic_dkms OFA_DIR="$OFA_DIR" "$@"
}

if [ ${STAGE} == "CONFIGURE" ]; then
	(cd mlnx-ofed-kernel && configure_mlnx_ofed_kernel)

	#(cd knem && configure_knem) || exit 2
elif [ ${STAGE} == "BUILD" ]; then
	# Build mlnx-ofed-kernel (see ../mlnx-ofed-kernel/debian/rules)
	(cd mlnx-ofed-kernel && build_mlnx_ofed_kernel)

	# Build isert (see ../isert/debian/rules)
	(cd isert && build_generic_dkms_ofa) || exit 2

	# Build iser (see ../iser/debian/rules)
	(cd iser && build_generic_dkms_ofa) || exit 2

	# Build knem (see ../knem/debian/rules)
	#(cd knem && build_knem) || exit 2

	# Build mlnx-nfsrdma (see ../mlnx-nfsrdma/debian/rules)
	(cd mlnx-nfsrdma && build_generic_dkms_ofa) || exit 2

	# Build mlnx-nvme (see ../mlnx-nvme/debian/rules)
	# (cd mlnx-nvme && build_generic_dkms_ofa CONFIG_NVME_HOST_WITHOUT_FC=) || exit 2

	# Build srp (see ../srp/debian/rules)
	(cd srp && build_generic_dkms_ofa) || exit 2

	# Build kernel-mft (see ../kernel-mft/debian/rules)
	#
	# For some reason the makefiles are not using KDIR and KVER variables, but KSRC
	# and KPVER. Pass these as extra arguments, otherwise the makefiles will use
	# `uname` to find which kernel version to use.
	#
	(cd kernel-mft && build_generic_dkms KSRC="$KDIR" KPVER="$KVER") || exit 2
else
	echo "BUILD FAILED: Please specify a correct command"
	exit 1
fi


