mkfile_path := $(abspath $(lastword $(MAKEFILE_LIST)))
mkfile_dir := $(dir $(mkfile_path))
PROJECTDIR := $(mkfile_dir)../../..
UNAME := $(shell uname -r)

bwpci-objs := bwpci_char.o bwpci_ioctl.o 
obj-m   := bwpci.o 

KERNELDIR  ?= /lib/modules/$(shell uname -r)/build
PWD        := $(shell pwd)
ccflags-y  := -I$(PROJECTDIR)/include -I$(PROJECTDIR)/common/include -fno-aggressive-loop-optimizations
MODDIR     ?= /lib/modules/$(shell uname -r)/kernel/drivers/misc
MODULE     ?= bwpci.ko

ifneq ("$(wildcard /usr/src/linux-headers-$(UNAME)/include/config/modversions.h)", "")
	ccflags-y := -DMODVERSIONS $(ccflags-y)
endif

all: get_user_pages_api_version.h bwbuild.h
	$(MAKE) -C $(KERNELDIR) M=$(PWD)

# For installed versions of the driver where there is no git repository
simple:  
	$(MAKE) -C $(KERNELDIR) M=$(PWD)

get_user_pages_api_version.h:
	./prebuild.sh

bwbuild.h:
ifneq ("$(REVISION)", "")
	python3 $(PROJECTDIR)/tools/scripts/bwgitv.py --gitdir=$(PROJECTDIR) $(PROJECTDIR)/common/include/bwbuild.repo $(PROJECTDIR)/include/bwbuild.h --revision=$(REVISION)
else
	python3 $(PROJECTDIR)/tools/scripts/bwgitv.py --gitdir=$(PROJECTDIR) $(PROJECTDIR)/common/include/bwbuild.repo $(PROJECTDIR)/include/bwbuild.h
endif

install: all

# For installed versions of the driver where there is no git repository
install_simple: simple 

install install_simple:
	cp $(PWD)/bwpci.ko $(MODDIR)/$(MODULE)
	chmod 744 $(MODDIR)/$(MODULE)
	cp bwpcidrv.h /usr/include/linux
	cp 80-bwpcie.rules /etc/udev/rules.d/
	cp bwpcied /etc/init.d

clean:
	rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions *.ko.unsigned modules.order Module.symvers get_user_pages_api_version.h $(PROJECTDIR)/include/bwbuild.h


