COREPATH ?=../..
DEFSPATH ?=$(COREPATH)/..
.DEFAULT_GOAL := all

include $(DEFSPATH)/Makefile.defs

LIB_LDFLAGS  += $(module_ldflags)
CPPFLAGS += -I $(COREPATH)
CFLAGS   += -I $(COREPATH)
CFLAGS   += $(module_cflags)
CPPFLAGS += $(module_cflags)
CXXFLAGS += $(module_cflags)

app_module_dir ?= $(COREPATH)/lib

lib_name = $(plug_in_name).so
lib_full_name ?= $(app_module_dir)/$(lib_name)

module_conf_files =  $(notdir $(wildcard etc/*.conf))
AUDIO_FILES=$(notdir $(wildcard wav/*.wav))
EXTRA_LIB_DIR?=lib/
EXTRA_LIB_FILES=$(filter-out CMakeLists.txt, $(notdir $(wildcard $(EXTRA_LIB_DIR)*)))

srcs     = $(wildcard *.cpp)
hrds     = $(wildcard *.h)
objs     = $(srcs:.cpp=.o) 
depends  = $(srcs:.cpp=.d)

.PHONY: all
all: $(extra_target) $(lib_full_name)

.PHONY: module_package
module_package: $(extra_target) $(lib_name)

.PHONY: clean
clean: $(extra_clean)
	@rm -f $(objs) $(depends) $(lib_name)

.PHONY: install
install: all $(extra_install) $(DESTDIR)$(modules_prefix)/$(modules_dir)
	if [ -f "$(lib_name)" ]; then \
	 $(INSTALL_MODULES) $(lib_name) $(DESTDIR)$(modules_prefix)/$(modules_dir); \
	fi

.PHONY: install-cfg
install-cfg: $(DESTDIR)$(app_cfg_target)
	@set -e; \
	for r in $(module_conf_files); do \
			echo installing $$r ;  \
			sed -e "s#/usr/.*lib/sems/audio/#$(audio_target)#g" \
			-e "s#/usr/.*lib/sems/plug-in/#$(modules_target)#g" \
			-e "s#/usr/.*lib/sems/ivr/#$(lib_target)ivr/#g" \
			-e "s#/usr/.*lib/sems/dsm/#$(lib_target)dsm/#g" \
			-e "s#/usr/.*lib/sems/py_sems/#$(lib_target)py_sems/#g" \
			-e "s#/usr/.*etc/sems#$(app_cfg_target)#g" \
			< etc/$$r > $(DESTDIR)$(app_cfg_target)$$r; \
	done

$(DESTDIR)$(audio_prefix)/$(audio_dir):
	mkdir -p $(DESTDIR)$(audio_prefix)/$(audio_dir)

.PHONY: $(plug_in_name)_audio
$(plug_in_name)_audio: $(DESTDIR)$(audio_prefix)/$(audio_dir)
	mkdir -p $(DESTDIR)$(audio_prefix)/$(audio_dir)$(plug_in_name)
	@set -e; \
	for f in $(AUDIO_FILES) ; do \
		if [ -n "wav/$$f" ]; then \
			$(INSTALL_AUDIO) wav/$$f $(DESTDIR)$(audio_prefix)/$(audio_dir)$(plug_in_name)/$$f; \
		fi ; \
	done

.PHONY: $(plug_in_name)_lib
$(plug_in_name)_lib: 
	mkdir -p $(DESTDIR)$(lib_prefix)/$(lib_dir)/$(plug_in_name)
	@set -e; \
	for f in $(EXTRA_LIB_FILES) ; do \
		if [ -n "$(EXTRA_LIB_DIR)/$$f" ]; then \
			$(INSTALL_AUDIO) $(EXTRA_LIB_DIR)$$f $(DESTDIR)$(lib_prefix)/$(lib_dir)/$(plug_in_name)/$$f; \
		fi ; \
	done

%.o: %.cpp $(DEFSPATH)/Makefile.defs
	$(CXX) -MMD $(CXXFLAGS) $(CPPFLAGS) -c $< -o $@

%.o: %.c $(DEFSPATH)/Makefile.defs
	$(CC) -MMD $(CFLAGS) $(CPPFLAGS) -c $< -o $@

$(lib_full_name): $(lib_name)
ifneq ($(lib_full_name),$(lib_name))
ifneq ($(lib_full_name),./$(lib_name))
	cp $(lib_name) $(lib_full_name)
endif
endif

-include $(depends)

$(lib_name): $(objs) $(module_extra_objs) Makefile
	$(LD) -o $(lib_name) $(objs) $(module_extra_objs) $(LIB_LDFLAGS)

