KERNELDIR := /lib/modules/$(shell uname -r)/build/

POSSIBLE_KERNEL_DIRS := /lib/modules/$(shell uname -r)/build/ /usr/src/linux-$(shell uname -r)/ /usr/src/linux

KERNELDIR := $(patsubst %/include,%,$(firstword $(wildcard $(patsubst %,%/include,$(POSSIBLE_KERNEL_DIRS)))))

EXTRA_CFLAGS  := -O2 -DMODULE -D__KERNEL__ ${WARN} ${INCLUDE}
PWD := $(shell pwd)
MODULE_SRC := $(if $(M),$(M),$(PWD))

KERNELVER := $(notdir $(patsubst %/build/,%,$(KERNELDIR)))
KERNELVER := $(patsubst linux-%,%,$(KERNELVER))
KERNELVER := $(patsubst source-%,%,$(KERNELVER))
KERNELVER := $(patsubst headers-%,%,$(KERNELVER))

SRC1 := $(wildcard $(MODULE_SRC)/*.c )
SRC2 := $(filter-out %.mod.c,$(SRC1))
SRC3 := $(patsubst %.c,%.o,$(SRC2))

OBJECTS := $(notdir $(SRC3))
MODULE := $(notdir $(MODULE_SRC) )

obj-m	+=		$(MODULE).o
$(MODULE)-objs:=		$(OBJECTS)


ifeq ($(KERNELRELEASE),)
default:
	clear;$(MAKE) -C $(KERNELDIR) M=$(PWD) modules

endif

clean:
	rm -f *~ *.o *.ko Module.symvers *.mod.c .*.cmd

veryclean:
	rm -f *~ *.o *.ko Module.symvers *.mod.c .*.cmd
	find . -name \*.ko -exec rm {} \; || true
	find . -type d -exec rmdir {} 2>/dev/null \; || true

%.show:
	@echo "$*=$($*)"

#
#
#KERNEL_CANDIDATES := $(wildcard 2.6.*)
#
#allversions:	$(KERNEL_CANDIDATES:=.kernelversion)
#
#%.kernelversion:
#	@echo "Building for $*"
#	$(MAKE) clean
#	$(MAKE) -C /usr/src/linux-headers-$* M=$(PWD) modules
#	mkdir -vp $(notdir $*)
#	cp -v $(obj-m:.o=.ko) $(notdir $*)
#
#
BUILD_LIST := $(shell cat $(wildcard kernelversions) /dev/null | grep -v "^\#" | sed "s/:/@/g" )
BUILD_TARGETS := $(BUILD_LIST:=.buildfor)

build2kernel = $(word 1,$(subst @, ,$(1)))
build2srcloc = $(word 2,$(subst @, ,$(1)))

buildforall:	$(BUILD_TARGETS)
allversions:	$(BUILD_TARGETS)

%.buildfor:
	@echo BUILDING $(call build2srcloc,$*)
	@echo FOR $(call build2kernel,$*)
	$(MAKE) clean
	$(MAKE) -C $(call build2srcloc,$*) M=$(PWD) modules
	mkdir -vp $(call build2kernel,$*)
	cp -v $(obj-m:.o=.ko) $(call build2kernel,$*)
