MODNAME=NiViPciK
MODDEPS=nikal nipalk 
ifeq (,$(MODNAME))
$(error MODNAME is unset.  MODNAME must be set to the basename of the module to be built.)
endif

# Kbuild inputs:
#   INSTALL_MOD_DIR:  the kernel module tree subdirectory to install
#                     a module to
#   INSTALL_MOD_PATH: alternate root location for the /lib/modules tree
#                     to install the module under
INSTALL_MOD_DIR=extra/natinst
INSTALL_MOD_PATH=

# Internal variables
#   KERNELVER:        kernel version number/name to build against
#   KERNELDIR:        location of the build Makefile being used to
#                     build the kernel module
#   SYMVERDIR:        the directory to cache per-module symbol version
#                     definitions
#   DEBUG:            enable additional debugging information, both during
#                     build as well as in the built kernel module
MODULEDIR=$(shell pwd)
KERNELVER=$(shell uname -r)
KERNELDIR=/lib/modules/$(KERNELVER)/build
SYMVERDIR=/var/lib/nikal/$(KERNELVER)/symvers
DEBUG=

ifneq ($(DEBUG),)
Q=
else
Q=@
endif

# Top-level targets
.PHONY: all build install uninstall clean distclean
all: build

build: $(MODNAME).ko $(SYMVERDIR)/$(MODNAME).symvers
install: $(INSTALL_MOD_PATH)/lib/modules/$(KERNELVER)/$(INSTALL_MOD_DIR)/$(MODNAME).ko
install: $(SYMVERDIR)/$(MODNAME).symvers

uninstall:
	$(Q)rm -f $(INSTALL_MOD_PATH)/lib/modules/$(KERNELVER)/$(INSTALL_MOD_DIR)/$(MODNAME).ko 2> /dev/null

clean:
	$(Q)$(MAKE) --no-print-directory -s -C $(KERNELDIR) M=$(MODULEDIR) $(if $(Q),,Q="") clean

distclean: clean uninstall
	$(Q)rm -f $(SYMVERDIR)/$(MODNAME).symvers 2> /dev/null

# build rules
# INSTALL_MOD_STRIP removes debug symbols if the value is 1
# no stripping otherwise
# https://www.kernel.org/doc/Documentation/kbuild/kbuild.txt
$(INSTALL_MOD_PATH)/lib/modules/$(KERNELVER)/$(INSTALL_MOD_DIR)/$(MODNAME).ko: $(MODNAME).ko
	$(Q)echo Installing $<
	$(Q)$(MAKE) --no-print-directory -C $(KERNELDIR) M=$(MODULEDIR) $(if $(Q),,Q="") INSTALL_MOD_DIR=$(INSTALL_MOD_DIR) $(if $(DEBUG),,INSTALL_MOD_STRIP=1) modules_install

$(SYMVERDIR)/$(MODNAME).symvers: Module.symvers
	$(Q)echo Installing $(MODNAME) symbol versions into:
	$(Q)echo $@
	$(Q)mkdir -p $(@D)
	$(Q)cp -f $< $@

Module.symvers: $(MODNAME).ko

# Add dependency on symvers files to ensure that build fails early and meaningfully
# if symbol information for depended-on modules is missing
$(MODNAME).ko: $(strip $(foreach _dep,$(MODDEPS),$(SYMVERDIR)/$(_dep).symvers ))

$(MODNAME).ko: $(MODNAME)-bin.o_shipped $(MODNAME)-interface.c
# Generate an empty .cmd file to suppress errors from the Kbuild MODPOST step.
	$(Q)touch .$(MODNAME)-bin.o.cmd
	$(Q)echo Making $@
	$(Q)$(MAKE) --no-print-directory -C $(KERNELDIR) M=$(MODULEDIR) $(if $(Q),,Q="") modules

