#!/bin/bash

# This script is used to generate the debian/dkms.in file from the modules
# built from this repository.
#
# To use it, on the target Ubuntu release and kernel:
#
# 1. Build all the modules locally:
#    ./debian/build_all.sh $(uname -r) /lib/modules/$(uname -r)/build/
#
# 2. Run this script that will pick up all generated .ko files in the
#    subdirectories:
#    ./debian/gen-dkms-conf-entries.sh > debian/dkms.in

set -e

cat <<EOF
PACKAGE_NAME="%DEB_SOURCE%"
PACKAGE_VERSION="%DEB_VERSION_UPSTREAM%"
CLEAN="echo CLEAN"
MAKE[0]="./build_all.sh \${kernelver} \${kernel_source_dir}"
AUTO_INSTALL="yes"
AUTOINSTALL="yes"
idx=0

check_config() {
	local config_symbol=\$1
	local config_file="/boot/config-\${kernelver}"
	[ ! -f "\$config_file" ] && config_file="/lib/modules/\${kernelver}/build/.config"

	if grep -qE "^\${config_symbol}=[ym]" "\$config_file"; then
		return 0
	fi
	return 1

}

should_build() {
	# These modules sometimes won't build due to config or architecture.
	# Check these exceptions, otherwise default to true.
	local module=\$1
	local arch=\$(uname -m)
	case "\$module" in
		fwctl)
			# Check if fwctl is inbox, the only one that will not be rebuilt by upstream
			if [ "\$arch" = "x86_64" ] && modinfo \$module >/dev/null 2>&1; then
                                false
                        else
                                true
                        fi
                        ;;
		ib_qib)
			check_config CONFIG_INFINIBAND_QIB
			;;
		hfi1)
			check_config CONFIG_INFINIBAND_HFI1
			;;
		opa_vnic)
			check_config CONFIG_INFINIBAND_OPA_VNIC
			;;
		rdmavt)
			check_config CONFIG_INFINIBAND_RDMAVT
			;;
		usnic_verbs)
			check_config CONFIG_INFINIBAND_USNIC
			;;
		bf3_livefish)
			[ "\$arch" = "aarch64" ]
			;;
		hns-roce-hw-v2)
			check_config CONFIG_INFINIBAND_HNS_HIP08
			;;
		*)
			true
			;;
	esac
	return \$?
}

EOF

find . -name '*.ko' | sort | while read -r line; do
	line=${line#./}
	base=$(basename "$line")
	built_module_name=${base%.ko}
	built_module_location=$(dirname "$line")
	dest_module_location="/extra"
	echo "if should_build "$built_module_name"; then"
	echo "	BUILT_MODULE_NAME[\$idx]=\"$built_module_name\""
	echo "	BUILT_MODULE_LOCATION[\$idx]=\"$built_module_location\""
	echo "	DEST_MODULE_LOCATION[\$idx]=\"$dest_module_location\""
	echo "	((idx++))"
	echo "fi"
	echo
done
