MAJOR=$(shell uname -r | sed -e "s/\([0-9]*\).*$$/\1/")
MINOR=$(shell uname -r | sed -e "s/[0-9]*.\([0-9]*\).*\$$/\1/")
REV=$(shell uname -r | sed -e "s/[0-9]*.[0-9]*.\([0-9]*\).*$$/\1/")

#kernel major version 2.x
ifeq ($(MAJOR),2)
ifeq ($(MINOR),6)
	CALL_SUBDIR=$(shell if [ $(REV) -ge 18 ];then echo ./2.6.18_3.4/;fi )
	CALL_SUBDIR_DEV=$(shell echo ./2.6.18_3.4/ )
	INSMOD_DEVNAME=$(shell echo ccomdrvusb.ko;)
endif
endif
# kernel major version 3.x
ifeq ($(MAJOR),3)
	CALL_SUBDIR=$(shell if [ $(MINOR) -le 4 ];then echo ./2.6.18_3.4/; elif [ $(MINOR) -ge 6 ];then echo ./3.6_or_newer/;elif [ $(MINOR) -eq 5 ];then echo ./3.5/;fi )
	CALL_SUBDIR_DEV=$(shell if [ $(MINOR) -le 4 ];then echo ./2.6.18_3.4/; elif [ $(MINOR) -ge 6 ];then echo ./3.6_or_newer/;else echo ./3.5/;fi )
	INSMOD_DEVNAME=$(shell if [ $(MINOR) -eq 5 ];then echo vizzini.ko;else echo ccomdrvusb.ko;fi )
endif
# kernel major version 4.x
ifeq ($(MAJOR),4)
        CALL_SUBDIR=$(shell echo ./3.6_or_newer/;)
        CALL_SUBDIR_DEV=$(shell echo ./3.6_or_newer/;)
        INSMOD_DEVNAME=$(shell echo ccomdrvusb.ko;)
endif
# kernel major version 5.x
ifeq ($(MAJOR),5)
        CALL_SUBDIR=$(shell echo ./3.6_or_newer/;)
        CALL_SUBDIR_DEV=$(shell echo ./3.6_or_newer/;)
        INSMOD_DEVNAME=$(shell echo ccomdrvusb.ko;)
endif
# kernel major version 6.x
ifeq ($(MAJOR),6)
        CALL_SUBDIR=$(shell echo ./3.6_or_newer/;)
        CALL_SUBDIR_DEV=$(shell echo ./3.6_or_newer/;)
        INSMOD_DEVNAME=$(shell echo ccomdrvusb.ko;)
endif
# kernel major version 7.x
ifeq ($(MAJOR),7)
        CALL_SUBDIR=$(shell echo ./3.6_or_newer/;)
        CALL_SUBDIR_DEV=$(shell echo ./3.6_or_newer/;)
        INSMOD_DEVNAME=$(shell echo ccomdrvusb.ko;)
endif

all:
ifeq ($(shell uname -r), 4.9.140-tegra)
	cd /lib/modules/4.9.140-tegra/ && ln -sf /usr/src/linux-headers-4.9.140-tegra-ubuntu18.04_aarch64/kernel-4.9 build
endif
ifeq ($(strip $(CALL_SUBDIR)),)
	$(error "current kernel=$(MAJOR).$(MINOR).$(REV) version cannot build.")
ifeq ($(MAJOR),2)
	$(error "<2.6.18 or later>")
endif
endif
	$(MAKE) -C $(CALL_SUBDIR)

force:
	$(MAKE) -C $(CALL_SUBDIR_DEV)

install:
ifeq ($(strip $(CALL_SUBDIR)),)
	$(error "current kernel=$(MAJOR).$(MINOR).$(REV) version cannot build.")
ifeq ($(MAJOR),2)
	$(error "<2.6.18 or later>")
endif
endif
	$(MAKE) -C $(CALL_SUBDIR) modules_install
	ln -s $(CALL_SUBDIR)$(INSMOD_DEVNAME) $(INSMOD_DEVNAME)

force-install:
	$(MAKE) -C $(CALL_SUBDIR_DEV) modules_install
	ln -s $(CALL_SUBDIR_DEV)$(INSMOD_DEVNAME) $(INSMOD_DEVNAME)

clean:
ifeq ($(strip $(CALL_SUBDIR)),)
	$(error "current kernel=$(MAJOR).$(MINOR).$(REV) version cannot build.")
ifeq ($(MAJOR),2)
	$(error "<2.6.18 or later>")
endif
endif
	$(MAKE) -C $(CALL_SUBDIR) clean
	rm -f $(INSMOD_DEVNAME)

force-clean:
	$(MAKE) -C $(CALL_SUBDIR_DEV) clean
	rm -f $(INSMOD_DEVNAME)


