# Makefile for the ip_wccp kernel module
#
# ChangeLog
#
# Version 1.6.2:
#
#  - Cleaned up the kernel build glue to make it easier to build
#    for other kernel versions than the currently running kernel
#  - Warn if running kernel does not match kernel sources
#  - Error out if the kernel source is not configured
#  - Automatically "depmod -a" while installing the module
#
# Version 1.6:
#
#  - Initial release

ifeq ($(VERSION),)

KERNELSRC=/lib/modules/$(shell uname -r)/build
CONFIG_FILE  := $(KERNELSRC)/include/linux/config.h
VERSION_FILE := $(KERNELSRC)/include/linux/version.h

#check if config.h file exists
ifeq (,$(wildcard $(CONFIG_FILE)))
$(error Linux kernel source not configured - config.h not found)
endif

#check if version.h file exists
ifeq (,$(wildcard $(VERSION_FILE)))
$(error Linux kernel source not configured - version.h not found)
endif

# check if the running kernel matches the source.
KERNEL_VERSION := $(shell $(CC) $(CFLAGS) -E -dM $(VERSION_FILE) | grep UTS_RELEASE | \
	awk '{ print $$3 }' | sed 's/\"//g')

ifneq ($(KERNEL_VERSION),$(shell uname -r))
$(warning *-)
$(warning *- Warning: The running kernel ($(shell uname -r)))
$(warning *- does not match with the kernel source version ($(KERNEL_VERSION)))
$(warning *-)
$(shell sleep 1)
endif

MAJOR_VERSION := $(shell echo $(KERNEL_VERSION) | cut -d. -f1-2)

.PHONY: module install install_module clean depmod

ifeq ($(MAJOR_VERSION),2.4)
# Linux-2.4
module: ip_wccp.o

ip_wccp.o:
	make -C $(KERNELSRC) SUBDIRS=$$PWD modules

install_module: module
	mkdir -p /lib/modules/$(shell uname -r)/extra
	cp ip_wccp.o /lib/modules/$(shell uname -r)/extra/

install: install_module depmod
else
# Linux-2.6 and later
module: ip_wccp.ko

ip_wccp.ko:
	make -C $(KERNELSRC) M=$$PWD modules

install_module: module
	make -C $(KERNELSRC) M=$$PWD modules_install

install: install_module depmod
endif

modules: module
modules_install: install

clean:
	rm -rf *.o *.ko *.mod.c .built-in.o.cmd .ip_wccp.* .tmp_versions

depmod:
ifeq ($(KERNEL_VERSION),$(shell uname -r))
	depmod -a
else
	@echo "*-"
	@echo "*- Notice: depmod -a not automatically run when building for"
	@echo "*- another kernel version."
	@echo "*-"
	@sleep 1
endif

else

# Called from the kernel Makefile

obj-m += ip_wccp.o

# Linux-2.4 needs a little glue to build custom modules..
ifeq ($(MAKING_MODULES),1)
modules:
	gcc -c $(CFLAGS) ip_wccp.c
endif

endif
