#!/usr/bin/make -f
# ------------------------------------------------------------------------------
# CORAS(LNX) for VPC/Solution-ePC/EPC/LPC
# coras kernel module
# 
# Copyright (c) Since 2021 CONTEC Co.,Ltd. All Rights reserved.
# ------------------------------------------------------------------------------

# check kernel major version
ifneq ($(shell uname -r | cut -c-2), $(filter $(shell uname -r | cut -c-2), 3. 4. 5. 6.))
$(warning "This Kernel version is maybe not supported.")
endif

SUBDIR := $(shell pwd)

# systemctl(systemd)
INITSERVICE ?= systemd

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

INST_PATH ?= /opt/contec/CoRasMod
MOD_PATH ?= module/

DESTDIR ?= 

SYSTEMDDIR ?= /lib/systemd/system
#SYSTEMDDIR ?= /usr/lib/systemd/system
INST_MODPATH ?= $(INST_PATH)

obj-m := coras.o

all: modules config

config:
	sed -e 's:@INSTMODPATH@:$(INST_MODPATH):g' < ./coras_load.sh.in > ./coras_load.sh
	sed -e 's:@INSTSHPATH@:$(INST_PATH):g' < ./coras_load.service.in > ./coras_load.service

install: module_install
#	$(MAKE) -C $(KERNEL_SRC) M=$(SUBDIR) modules_install

uninstall: module_uninstall

modules:
	$(MAKE) -C $(KERNEL_SRC) M=$(SUBDIR)

module_install:
#	install -m 0644 -D $(SUBDIR)/coras.ko $(DESTDIR)$(INST_MODPATH)/coras.ko
	install -m 0744 -D ./coras_load.sh $(DESTDIR)$(INST_PATH)/coras_load.sh
	install -m 0744 -D ./coras_unload.sh $(DESTDIR)$(INST_PATH)/coras_unload.sh
	install -m 0644 -D ./coras_load.service $(DESTDIR)$(SYSTEMDDIR)/coras_load.service
#	systemctl daemon-reload

service_start:
	systemctl enable --now coras_load

service_stop:
	systemctl disable --now coras_load

module_uninstall:
	systemctl disable --now coras_load
	rm -f $(DESTDIR)$(INST_MODPATH)/coras.ko
	rm -f $(DESTDIR)$(INST_PATH)/coras_load.sh
	rm -f $(DESTDIR)$(INST_PATH)/coras_unload.sh
	if [ -d "$(DESTDIR)$(INST_MODPATH)" ]; then \
	  rmdir $(DESTDIR)$(INST_MODPATH);          \
	fi
	if [ -d "$(DESTDIR)$(INST_PATH)" ]; then \
	  rmdir $(DESTDIR)$(INST_PATH);          \
	fi
	rm -f $(DESTDIR)$(SYSTEMDDIR)/coras_load.service

clean:
	$(MAKE) -C $(KERNEL_SRC) M=$(SUBDIR) clean
	rm -f *.o *~ core .depend .*.cmd *.ko *.mod.c
	rm -f Module.markers Module.symvers modules.order
	rm -rf .tmp_versions Modules.symvers
	rm -f module/*.ko
	rm -f coras_load.sh
	rm -f coras_load.service

coras.o: coras.c
