# step 3: copy package lists referenced in distro configuration
#         (and only those!) over to $(BUILDDIR)

ifndef BUILDDIR
$(error BUILDDIR not defined)
endif

include $(BUILDDIR)/distcfg.mk
SUFFIX := pkg/lists
TARGET := $(BUILDDIR)/$(SUFFIX)

# Metadata/ needed only for installers (and not for e.g. syslinux.iso)
# FIXME: installable live needs it too, don't move to install2 feature
### see also .../features.in/build-distro/lib/build-distro.mk
ifneq (,$(findstring install2,$(FEATURES)))
DOTBASE := dot-base
endif

all: $(TARGET) $(GLOBAL_DEBUG) $(DOTBASE) copy-lists copy-groups
	@if type -t git >&/dev/null && cd $(TARGET); then \
		if [ -n "`git status -s`" ]; then \
			git add . && \
			git commit -qam "requested $(SUFFIX) copied over"; \
		fi; \
		cd - >&/dev/null; \
	fi

# env | sort -u | grep _LISTS | xargs cp
copy-lists:
	@cp --parents -at $(TARGET) -- \
		$(foreach V, \
			$(filter %_LISTS,$(sort $(.VARIABLES))), \
			$(if $(filter environment% file,$(origin $V)),$($V)))

copy-groups:
	@if [ -n "$(THE_GROUPS)$(MAIN_GROUPS)" ]; then \
		cp -at $(TARGET) -- $(THE_GROUPS) $(MAIN_GROUPS); \
	fi

# args: name, suffix, command
define dump-THEM
if [ -n "$($(1)_$(2))" ]; then echo -e "\n## $(1)_$(2)"; $(3) $($(1)_$(2)); fi;
endef

dump-PACKAGES = $(call dump-THEM,$(1),PACKAGES,echo)
dump-LISTS = $(call dump-THEM,$(1),LISTS,cat)

dot-base:
	@# construct .base packagelist for alterator-pkg
	@{ \
		echo "## generated by pkg.in/lists/Makefile"; \
		$(foreach p,SYSTEM COMMON THE BASE,$(call dump-PACKAGES,$(p))) \
		$(foreach l,THE BASE,$(call dump-LISTS,$(l))) \
	} | sed -re '/^[^[:space:]#]/ s/[[:space:]]+/\n/g' >$(TARGET)/.base

# do beforehand as foreach gets expanded before recipe execution
$(TARGET):
	@mkdir -p $(TARGET)

# figure out *_LISTS variables and print them out nicely
debug:
	@echo -e $(foreach V, \
		$(filter %_LISTS,$(sort $(.VARIABLES))), \
		$(if $(filter environment% file,$(origin $V)),\
			$(shell echo '\\n"**"' $V: $($V)))) '\n'

