# Copyright (c) 2017, Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU General Public License,
# version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.

KERNEL_SRC ?= /lib/modules/$(shell uname -r)/build

RELEASE_FILE := include/config/kernel.release

ifneq ($(wildcard $(O)/$(RELEASE_FILE)),)
KERNEL_BUILD := $(O)
else ifneq ($(wildcard $(KERNEL_SRC)/$(RELEASE_FILE)),)
KERNEL_BUILD := $(KERNEL_SRC)
else
$(error Unable to detect kernel build tree. Please specify it as KERNEL_SRC param)
endif

KERNEL_RELEASE := $(shell cat $(KERNEL_BUILD)/include/config/kernel.release)
KERNEL_MODULES := /lib/modules/$(KERNEL_RELEASE)/extra/zonesort

BUILD_MODULES_SIGN := false

$(info == zonesort build configuration:)
$(info MODULE_VERSION:          $(MODULE_VERSION))
$(info KERNEL_BUILD:            $(KERNEL_BUILD))
$(info KERNEL_RELEASE:          $(KERNEL_RELEASE))
$(info KERNEL_MODULES:          $(KERNEL_MODULES))
$(info BUILD_MODULES_SIGN:      $(BUILD_MODULES_SIGN))

# define kernel config for the MIC
KCONFIG += CONFIG_INTEL_ZONESORT=m
KCONFIG += CONFIG_INTEL_ZONESORT_VERSION=$(MODULE_VERSION)

INSTALL = install
INSTALL_d = $(INSTALL) -d
INSTALL_x = $(INSTALL)
INSTALL_f = $(INSTALL) -m644

.PHONY: all install modules clean
.PHONY: modules_install
.PHONY: modules_sign

all: modules

install: modules_install

# TODO: implement module signing
modules_sign:
	xpps-modsign.sh --modules-dir $(CURDIR)

ifeq ($(BUILD_MODULES_SIGN),true)
modules_install: modules_sign
endif

modules:
	$(MAKE) -j $(PARALLEL) -C $(KERNEL_BUILD) M=$(CURDIR) $(KCONFIG) $@

clean:
	$(MAKE) -j $(PARALLEL) -C $(KERNEL_BUILD) M=$(CURDIR) $(KCONFIG) clean

modules_install: modules
	$(INSTALL_d) $(DESTDIR)$(KERNEL_MODULES)
	$(INSTALL_f) zonesort/zonesort.ko $(DESTDIR)$(KERNEL_MODULES)
