#  Makefile to compile NI-KAL clients against the kernel
#
#  (C) Copyright 2002-2015
#  National Instruments Corporation.
#  All Rights reserved.


# KERNELRELEASE is set, so we're being invoked from the kernel build system
ifneq ($(KERNELRELEASE),)
   # module.mak provides CLIENT_MODULE, CLIENT_NAME, and CLIENT_MOD_DIR
   include $(src)/module.mak

   MODULE_RESYMS_FILE := $(notdir $(CLIENT_MODULE)).resyms
   EXTRA_CFLAGS := -I$(src)/../nikal/

   CLIENT_COPYRIGHT   := $(shell strings $(CLIENT_MODULE) | grep nNIVersion_LegalCopyright | sed 's/nNIVersion_LegalCopyright\=//')
   ifneq ($(CLIENT_COPYRIGHT),)
      EXTRA_CFLAGS += -DnNIKAL100_kCopyrightString="$(moduleCopyright)"
   endif

   CLIENT_AUTHOR      := $(shell strings $(CLIENT_MODULE) | grep nNIVersion_CompanyName | sed 's/nNIVersion_CompanyName\=//')
   ifneq ($(CLIENT_AUTHOR),)
      EXTRA_CFLAGS += -DnNIKAL100_kAuthorString="$(moduleAuthor)"
   endif

   CLIENT_DESCRIPTION := $(shell strings $(CLIENT_MODULE) | grep nNIVersion_FileDescription | sed 's/nNIVersion_FileDescription\=//')
   ifneq ($(CLIENT_DESCRIPTION),)
      EXTRA_CFLAGS += -DnNIKAL100_kDescriptionString="$(moduleDescription)"
   endif

   obj-m := $(CLIENT_NAME).o
   $(CLIENT_NAME)-objs := $(CLIENT_NAME)-interface.o $(CLIENT_NAME)-processed.o

# Processing of client module, including symbol renaming
$(obj)/$(CLIENT_NAME)-interface.c: $(CLIENT_MODULE)
	@$(src)/processmodule.sh --cmd_geninterface --module=$(CLIENT_MODULE) > $@

$(src)/$(MODULE_RESYMS_FILE): $(CLIENT_MODULE)
	@$(src)/processmodule.sh --cmd_updatesymrename --symfile=$@ --module=$(CLIENT_MODULE)

$(obj)/$(CLIENT_NAME)-processed.o_shipped : $(CLIENT_MODULE) $(src)/$(MODULE_RESYMS_FILE)
	@objcopy --redefine-syms=$(src)/$(MODULE_RESYMS_FILE) --rename-section .ctors=.ni_ctors --rename-section .init_array=.ni_init_array --remove-section .exportedSymbols $< $@

# KERNELRELEASE is not set, so this is a command-line invocation
else
   # module.mak provides CLIENT_MODULE, CLIENT_NAME, and CLIENT_MOD_DIR
   include module.mak

   # Provides MODPATH and KERNELDIRECTORY
   include ../nikal/Makefile.in

   PWD := $(shell pwd)

.PHONY: all install clean
all: $(CLIENT_NAME).ko

install: $(MODPATH)/$(CLIENT_MOD_DIR)/$(CLIENT_NAME).ko

clean:
	@$(MAKE) --no-print-directory -C $(KERNELDIRECTORY) M=$(PWD) INSTALL_MOD_DIR=kernel/natinst/$(CLIENT_MOD_DIR) clean
	@rm -rf *-interface.c *.resyms *.o_shipped .tmp_versions *.o .*.cmd *.mod.c shortsyms.txt

$(MODPATH)/$(CLIENT_MOD_DIR)/$(CLIENT_NAME).ko: $(CLIENT_NAME).ko
	@mkdir -p $(MODPATH)/$(CLIENT_MOD_DIR)
	@$(MAKE) --no-print-directory -C $(KERNELDIRECTORY) M=$(PWD) INSTALL_MOD_DIR=kernel/natinst/$(CLIENT_MOD_DIR) modules_install

$(CLIENT_NAME).ko: ../nikal/Makefile.in $(CLIENT_MODULE)
	-@touch $(CLIENT_MODULE)
	@$(MAKE) --no-print-directory -C $(KERNELDIRECTORY) M=$(PWD) modules

endif
