#*************************************************************************
# Copyright (c) 2011 UChicago Argonne LLC, as Operator of Argonne
#     National Laboratory.
# Copyright (c) 2002 The Regents of the University of California, as
#     Operator of Los Alamos National Laboratory.
# EPICS BASE is distributed subject to a Software License Agreement found
# in the file LICENSE that is included with this distribution.
#*************************************************************************

# RULES_EXPAND

vpath %@ $(USR_VPATH) $(ALL_SRC_DIRS)

#---------------------------------------------------------------
# Variable expansion

# Default settings
EXPAND_TOOL ?= $(PERL) $(TOOLS)/expandVars.pl

EXPANDFLAGS += -t $(INSTALL_LOCATION) -a $(T_A)
EXPANDFLAGS += $(addprefix -D ,$(EXPAND_VARS))

# The names of files to be expanded must end with '@'
EXPANDED = $(EXPAND:%@=%)

$(EXPANDED): %: %@
	$(ECHO) "Expanding $< to $@"
	@$(RM) $@
	@$(EXPAND_TOOL) $(EXPANDFLAGS) $($@_EXPANDFLAGS) $< $@

clean: expand_clean

expand_clean:
	@$(RM) $(EXPANDED)

.PRECIOUS: $(EXPANDED)
.PHONY: expand_clean

#---------------------------------------------------------------
# Assemblies (files assembled from snippets)

ASSEMBLE_TOOL ?= $(PERL) $(TOOLS)/assembleSnippets.pl

define COMMON_ASSEMBLY_template
$1_SNIPPETS += $$(foreach dir, .. $$(SRC_DIRS), \
    $$(wildcard $$(dir)/$$($1_PATTERN)))
$(COMMON_DIR)/$1: $$($1_SNIPPETS)
	$(ECHO) "Assembling common file $$@ from snippets"
	@$(RM) $1
	$(ASSEMBLE_TOOL) -o $1 $$^
	@$(MV) $1 $$@
endef
$(foreach asy, $(COMMON_ASSEMBLIES), \
    $(eval $(call COMMON_ASSEMBLY_template,$(strip $(asy)))))

define ASSEMBLY_template
$1_SNIPPETS += $$(foreach dir, .. $$(SRC_DIRS), \
    $$(wildcard $$(dir)/$$($1_PATTERN)))
$1: $$($1_SNIPPETS)
	$(ECHO) "Assembling file $$@ from snippets"
	@$(RM) $$@
	$(ASSEMBLE_TOOL) -o $$@ $$^
endef
$(foreach asy, $(ASSEMBLIES), \
    $(eval $(call ASSEMBLY_template,$(strip $(asy)))))

define ASSEMBLY_DEP_template
$1$(DEP):
	@echo $1: > $$@
endef
$(foreach asy, $(sort $(COMMON_ASSEMBLIES) $(ASSEMBLIES)), \
    $(eval $(call ASSEMBLY_DEP_template,$(strip $(asy)))))

