ifndef RAZER_MODULES
# This part runs as a normal, top-level Makefile:
X:=$(shell false)
KVER        ?= $(shell uname -r)
KBASE       ?= /lib/modules/$(KVER)
KSRC        ?= $(KBASE)/source
KBUILD      ?= $(KBASE)/build
MOD_DIR     ?= $(KBASE)/kernel
PWD         := $(shell pwd)
IDIR        := include/linux
RAZER_MODULES  := razer_kbd.o razer_tp.o
SHELL       := /bin/bash

ifeq ($(FORCE_EP_INTERVAL),1)
KBD_EP_INTERVAL := ep_interval=1
TP_EP_INTERVAL := ep_interval=1
else
KBD_EP_INTERVAL :=
TP_EP_INTERVAL :=
endif

ifneq ($(KERNELRELEASE),)
	obj-m  := $(RAZER_MODULES)
else
endif

DEBUG := 0

.PHONY: default clean modules load unload install
export RAZER_MODULES

#####################################################################
# Main targets

default: modules

# Build the modules razer_kbd.ko, razer_tp.ko
modules: $(KBUILD) $(patsubst %.o,%.c,$(RAZER_MODULES))
	$(MAKE) -C $(KBUILD) M=$(PWD) O=$(KBUILD) modules

clean:
	rm -f razer_kbd.mod.* razer_kbd.o razer_kbd.ko .razer_kbd.*.cmd
	rm -f razer_tp.mod.* razer_tp.o razer_tp.ko .razer_tp.*.cmd
	rm -f *~ diff/*~ *.orig diff/*.orig *.rej diff/*.rej
	rm -fr .tmp_versions Module.symvers modules.order

load: unload modules
	@( [ `id -u` == 0 ] || { echo "Must be root to load modules"; exit 1; } )
	{ insmod ./razer_kbd.ko $(KBD_EP_INTERVAL) debug=$(DEBUG) && insmod ./razer_tp.ko $(TP_EP_INTERVAL) debug=$(DEBUG); }; :
	@echo -e '\nRecent dmesg output:' ; dmesg | tail -10

unload:
	@( [ `id -u` == 0 ] || { echo "Must be root to unload modules"; exit 1; } )
	if lsmod | grep -q '^razer_kbd '; then rmmod razer_kbd; fi
	if lsmod | grep -q '^razer_tp '; then rmmod razer_tp; fi

install: modules
	@( [ `id -u` == 0 ] || { echo "Must be root to install modules"; exit 1; } )
	rm -f $(MOD_DIR)/drivers/input/keyboard/razer_kbd.ko
	rm -f $(MOD_DIR)/drivers/input/mouse/razer_tp.ko
	$(MAKE) -C $(KBUILD) M=$(PWD) O=$(KBUILD) modules_install
	depmod $(KVER)

#####################################################################
# Tools for preparing a release. Ignore these.

set-version:
	perl -i -pe 's/^(tp_smapi version ).*/$${1}$(VER)/' README
	perl -i -pe 's/^(#define TP_VERSION ").*/$${1}$(VER)"/' thinkpad_ec.c tp_smapi.c
	perl -i -pe 's/^(TP_VER := ).*/$${1}$(VER)/' Makefile
	perl -i -pe 's/^(PACKAGE_VERSION=").*/$${1}$(VER)"/' dkms.conf

TGZ=../tp_smapi-$(VER).tgz
create-tgz:
	git archive  --format=tar --prefix=tp_smapi-$(VER)/ HEAD | gzip -c > $(TGZ)
	tar tzvf $(TGZ)
	echo "Ready: $(TGZ)"

else
#####################################################################
# This part runs as a submake in kernel Makefile context:

EXTRA_CFLAGS := $(CFLAGS) -I$(M)/include
obj-m        := $(RAZER_MODULES)

endif
