#!/usr/bin/make -f
CC=gcc
INSTALL_MOD_DIR:=extra
KVERSION   ?= $(shell uname -r)
KERNEL_SRC :=  /lib/modules/$(KVERSION)
MOD_SRC_DIR:= $(shell pwd)
KBUILD_OUTPUT=$(KERNEL_SRC)/build

LIB_DIR = usr/lib/python3/dist-packages
CUSTOM_RULES_DIR := $(shell pwd)/debian

export  INSTALL_MOD_DIR top_srcdir KVERSION  KERNEL_SRC CC  KBUILD_OUTPUT  CUSTOM_RULES_DIR

include $(CUSTOM_RULES_DIR)/rule-tx.mk

#all product need common
COMPILE_DIRS = $(MODULE_DIRS)

clean_dirs = $(MODULE_DIRS)
clean_dirs += common

custom_clean_dirs := $(addprefix _clean_,$(clean_dirs) )
complie_clean_dirs := $(addprefix _clean_,$(CUSTOMS_DIRS) )


%:
	dh $@
build: $(CUSTOMS_DIRS)
	@echo "build success"

$(custom_clean_dirs):
	$(MAKE) -C $(patsubst _clean_%,%,$@) clean

$(complie_clean_dirs):
	$(MAKE) -C $(patsubst _clean_%,%,$@) clean

common_build :
	$(MAKE) -C  $(MOD_SRC_DIR)/common

$(COMPILE_DIRS): common_build
	$(MAKE) -C  $(MOD_SRC_DIR)/$@
	dh_testdir
	dh_installdirs
	#dh_installdirs -pplatform-modules-ruijie-$@ usr/local/bin
	cp -r $(MOD_SRC_DIR)/common/build/*  debian/platform-modules-ruijie-$@/
	cp -r $(MOD_SRC_DIR)/$@/build/*  debian/platform-modules-ruijie-$@/

$(CUSTOMS_DIRS): $(COMPILE_DIRS)
	$(MAKE) -C  $@
	@(for mod in $(MODULE_DIRS); do \
		cp -r $@/build/* $(MOD_SRC_DIR)/debian/platform-modules-ruijie-$${mod}/; \
		cd $(MOD_SRC_DIR)/$${mod}; \
		cp -r $(MOD_SRC_DIR)/common/lib/plat_hal $(MOD_SRC_DIR)/$${mod}/; \
		cp -r $(MOD_SRC_DIR)/common/lib/rjutil $(MOD_SRC_DIR)/$${mod}/; \
		cp -r $(MOD_SRC_DIR)/common/lib/eepromutil $(MOD_SRC_DIR)/$${mod}/; \
		cp -r $(MOD_SRC_DIR)/common/sonic_platform $(MOD_SRC_DIR)/$${mod}/; \
		cp $(MOD_SRC_DIR)/common/script/hal_pltfm.py $(MOD_SRC_DIR)/$${mod}/hal_pltfm.py; \
		cp $(MOD_SRC_DIR)/common/script/platform_util.py $(MOD_SRC_DIR)/$${mod}/platform_util.py; \
		cp $(MOD_SRC_DIR)/common/script/platform_intf.py $(MOD_SRC_DIR)/$${mod}/platform_intf.py; \
		python3 setup.py bdist_wheel -d $(MOD_SRC_DIR)/$${mod}/modules; \
		rm -rf $(MOD_SRC_DIR)/$${mod}/plat_hal; \
		rm -rf $(MOD_SRC_DIR)/$${mod}/rjutil; \
		rm -rf $(MOD_SRC_DIR)/$${mod}/eepromutil; \
		rm -rf $(MOD_SRC_DIR)/$${mod}/sonic_platform; \
		rm -rf $(MOD_SRC_DIR)/$${mod}/hal_pltfm.py; \
		rm -rf $(MOD_SRC_DIR)/$${mod}/platform_intf.py; \
		rm -rf $(MOD_SRC_DIR)/$${mod}/platform_util.py; \
		cd $(MOD_SRC_DIR); \
	done)

binary: binary-indep
	@echo "======================================================="

binary-indep:
	# Resuming debhelper scripts
	dh_testroot
	dh_install
	dh_installchangelogs
	dh_installdocs
	dh_systemd_enable
	dh_installinit
	dh_systemd_start
	dh_link
	dh_fixperms
	dh_compress
	dh_strip
	dh_installdeb
	dh_gencontrol
	dh_md5sums
	dh_builddeb
override_dh_usrlocal:

override_dh_pysupport:

clean: $(custom_clean_dirs)  $(complie_clean_dirs)
	dh_testdir
	dh_testroot
	dh_clean

.PHONY: build  $(COMPILE_DIRS) $(CUSTOMS_DIRS) binary binary-arch binary-indep clean