# Test passing $(1) to $(CC). If $(CC) succeeds, then echo $(1).
# Copy from https://github.com/NVIDIA/open-gpu-kernel-modules/blob/main/utils.mk
TEST_CC_ARG = \
 $(shell $(CC) -c -x c /dev/null -Werror $(1) -o /dev/null > /dev/null 2>&1 && \
   echo $(1))
ifeq ($(ARCH),ARM64)
	ARCH:=arm64
endif

SHELL := /bin/bash

ifneq ($(RDMA_ENABLED),)
	ifeq ($(RDMA_ENABLED),1)
		NVIDIA_VERSION := $(shell modinfo nvidia | grep '^version:' | awk '{print $$2}')
		ifeq ($(NVIDIA_VERSION),)
$(error RDMA_ENABLED=1 but NVIDIA driver not detected! Please install NVIDIA driver or set RDMA_ENABLED=0)
		endif
$(info >> NVIDIA driver version detected : $(NVIDIA_VERSION))
		NVIDIA_SRC := $(shell ls -d /usr/src/nvidia-$(NVIDIA_VERSION) 2>/dev/null || echo "")
$(info >> NVIDIA driver version detected: $(NVIDIA_VERSION)	at $(NVIDIA_SRC))

		# Find nv-p2p.h header
		NVIDIA_P2P_HEADER := $(shell find $(NVIDIA_SRC) -type f -name nv-p2p.h 2>/dev/null | head -n1)
		NVIDIA_P2P_DIR := $(dir $(NVIDIA_P2P_HEADER))

		ifeq ($(NVIDIA_P2P_HEADER),)
$(error RDMA_ENABLED=1 but nv-p2p.h not found in $(NVIDIA_SRC)!)
		endif

		ccflags-y += -DRDMA_ENABLED=1

		# Optional: Disable GPL_ONLY_SYMBOLS for some platforms
		# Set NO_GPL_ONLY_SYMBOLS=1 if you get "Unknown symbol nvidia_p2p_* (err -22)" errors
		ifdef NO_GPL_ONLY_SYMBOLS
			ifeq ($(NO_GPL_ONLY_SYMBOLS),1)
$(info >> NO_GPL_ONLY_SYMBOLS flag enabled)
				ccflags-y += -DNO_GPL_ONLY_SYMBOLS
			endif
		endif

		# Find Module.symvers in multiple locations (DKMS may clean build dir)
		NVIDIA_MODULE_SYMVERS := $(shell \
			find $(NVIDIA_SRC) -type f -name Module.symvers 2>/dev/null | head -n1 || \
			find /var/lib/dkms/nvidia/$(NVIDIA_VERSION)/build -name Module.symvers 2>/dev/null | head -n1 || \
			find /var/lib/dkms/nvidia/$(NVIDIA_VERSION)/$(shell uname -r) -name Module.symvers 2>/dev/null | head -n1 || \
			echo "")

		# If Module.symvers not found, try to build it automatically (optional)
		ifeq ($(NVIDIA_MODULE_SYMVERS),)
			ifneq ($(NVIDIA_SRC),)
$(warning >> Module.symvers not found - attempting to build NVIDIA modules...)
				NVIDIA_BUILD_RESULT := $(shell cd $(NVIDIA_SRC) && $(MAKE) modules > /tmp/nvidia-build.log 2>&1 && echo "success" || echo "failed")
				ifeq ($(NVIDIA_BUILD_RESULT),success)
					NVIDIA_MODULE_SYMVERS := $(shell find $(NVIDIA_SRC) -type f -name Module.symvers 2>/dev/null | head -n1)
$(warning >> Module.symvers successfully created at: $(NVIDIA_MODULE_SYMVERS))
				else
$(error >> Failed to build NVIDIA modules. Check /tmp/nvidia-build.log)
				endif
			endif
		endif

		ccflags-y += -DRDMA_ENABLED=1

		ifneq ($(NVIDIA_P2P_HEADER),)
$(info >> nv-p2p.h found at: $(NVIDIA_P2P_HEADER))
			ccflags-y += -I$(NVIDIA_P2P_DIR)
		endif

$(info >> Module.symvers found at: $(NVIDIA_MODULE_SYMVERS))
		KBUILD_EXTRA_SYMBOLS := $(NVIDIA_MODULE_SYMVERS)
	else
$(info >> RDMA_ENABLED is set to 0)
	endif
else
$(info >> RDMA_ENABLED not defined, defaulting to 0)
endif

DRIVERNAME = flex-x400

SRC-OBJS := HpdMngr.o LtcMngr.o DvDrvBoard.o SdiDrvBoard.o XDv_Helper.o XDvDrv_Properties.o XSdi_Helper.o X400DrvBoard.o X410DrvBoard.o DrvParam.o X4XXDrvBoard.o X4XXDrvBoardHelper.o KernelTime.o MailboxMngr.o BramStatusMngr.o ConfigurationSpaceMngr.o BufMngr.o CommonBufMngr.o DMABufMngr.o DMAMngr.o DrvDbg.o EventMngr.o KThreadMngr.o KernelObjectCommon.o PropertiesMngr.o ShadowRegisters.o SkelDrv.o SkelProperties.o USBufMngr.o CommonBufMngr_Linux.o DMAMngr_Linux.o EventMngr_Linux.o KernelObjects.o KernelSysCall.o USBufMngr_Linux.o DriverAccess.o DriverEntry.o InterlockedOp.o LinuxDrvHlp.o NvidiaP2PWrapper.o DrvDbg_Linux.o FPGA_DMAController_ADVLP.o PCIeBridge_ADVLP.o ClockReconstructionMngr.o DelayedStreamStarterMngr.o LowLatencyMngr.o UltimateLowLatencyMngr.o XDrvBoard.o Scp.o ScpDv.o ScpHelper.o Stream.o StreamProperties.o HDMIInfoFrames.o

# default to currently running kernel if KVER not specified
ifeq ($(KVER),)
	KVER := $(shell uname -r)
endif

KERNEL_MAJOR := $(shell echo $(KVER) | cut -d. -f1)

KDIR ?= /lib/modules/$(KVER)/build
INSTALLDIR ?= /lib/modules/$(KVER)
PWD := $(shell pwd)

# Conditionally add -mno-outline-atomics to CFLAGS if it is supported
CONDITIONAL_CFLAGS := $(call TEST_CC_ARG, -mno-outline-atomics)

ccflags-y += -DMEM_ALLOC_METHOD=Dynamic
ccflags-y += -w -DDBG=0 -DDRIVER -DNO_C_LIB
ccflags-y += $(CFLAGS)
ccflags-y += -Wno-error=incompatible-pointer-types
ccflags-y += $(CONDITIONAL_CFLAGS)

ifneq ($(KERNELRELEASE),)

obj-m := $(DRIVERNAME).o
$(DRIVERNAME)-objs := $(SRC-OBJS)

else

ifndef VERBOSE
.SILENT: all
endif

all: gencmd default

default:
		
	for file in *.o_shipped; do if ! file "$$file" | grep -q 'ELF'; then xxd -p -r "$$file" > "$${file/.o_shipped/}.c"; fi; done
	for file in *.h_shipped; do if ! file "$$file" | grep -q 'ELF'; then xxd -p -r "$$file" > "$${file/.h_shipped/}.h"; fi; done

		@trap '$(MAKE) shipped_cleanup' EXIT ; $(MAKE) -C $(KDIR) M=$(PWD) modules

gencmd:
		for file in $(BINARY-OBJS); do touch .$${file}.cmd; done

genbin:
		for file in $(BINARY-OBJS); do echo "X" > $${file/.o/}.o_shipped; done

install:
		# Driver installation
		cp $(DRIVERNAME).ko $(INSTALLDIR)/$(DRIVERNAME).ko
		cp $(DRIVERNAME).rules /etc/udev/$(DRIVERNAME).rules
		if [ ! -f /etc/udev/rules.d/010-$(DRIVERNAME).rules ]; then ln -sf /etc/udev/$(DRIVERNAME).rules /etc/udev/rules.d/010-$(DRIVERNAME).rules; fi
		depmod -a
		modprobe -rq $(DRIVERNAME)
		modprobe $(DRIVERNAME)
		@for files in /dev/$(DRIVERNAME)*; do if [ ! -r files ]; then ( dmesg | grep -i $(DRIVERNAME) ) | grep -i "System needs a restart" -o --colour=always; echo "">NULL; fi; done

		# Creating character devices if necessary
		-START_LINE=$$(dmesg | grep -n '=====' | tail -n 1 | sed -E 's/^(.+):.*/\1/') &&\
		dmesg | tail -n +$$START_LINE | grep -i '==MKNOD==' &&\
		rm -rf /dev/delta-x3* &&\
		rm -rf /dev/flex-x4* &&\
		rm -rf /dev/delta-gwy* &&\
		rm -rf /dev/delta-mbs* &&\
		eval $$(dmesg | tail -n +$$START_LINE | grep -i '==MKNOD==' | sed -E 's/^.*driver name: (.+), board index: (.+), major: (.+), minor: (.+)/mknod -m 666 \/dev\/\1\2 c \3 \4 ; /i') ||:

uninstall:
		# Driver uninstallation
		modprobe -r $(DRIVERNAME)
		rm $(INSTALLDIR)/$(DRIVERNAME).ko
		rm /etc/udev/$(DRIVERNAME).rules
		rm /etc/udev/rules.d/010-$(DRIVERNAME).rules

	
shipped_cleanup:
	for file in *.o_shipped; do if ! file "$$file" | grep -q 'ELF'; then rm -f "$${file/.o_shipped/}.c"; fi; done
	for file in *.h_shipped; do if ! file "$$file" | grep -q 'ELF'; then rm -f "$${file/.h_shipped/}.h"; fi; done

clean:
		rm -f *.o
		rm -f Module.symvers
		rm -f modules.order
		rm -f *.ko
		rm -f .*.cmd

endif
