# DO NOT EDIT: This file is programmatically generated and managed by an external tool.
# It is a standard file that is copied and maintained in every repository.
# Any changes will be overwritten.
#
# Repository command surface.
#
# Recursively loads shared Make modules and repository-specific modules from
# scripts/build.
#
# Modules share a single GNU Make namespace, allowing targets to depend on
# one another across files. Repository modules automatically replace shared
# modules with the same relative path. Shared libraries are searched in order,
# with the first matching module taking precedence.
#
# Optional scripts/build/config.mk controls shared module selection:
#   MAKE_INCLUDE_MODULES  Load only specified modules (default: all).
#   MAKE_EXCLUDE_MODULES  Exclude specified modules.
#
# Exclusions take precedence over inclusions. Local modules always load.
# Module identifiers are relative paths (e.g., docker/build.mk).
.DEFAULT_GOAL := help

REPO_ROOT := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST)))))

MAKE_REPO_MODULE_DIR ?= $(REPO_ROOT)/scripts/build
MAKE_REPO_CONFIG ?= $(MAKE_REPO_MODULE_DIR)/config.mk

MAKE_LIBRARY_DIRS ?= \
    $(HOME)/.mklib/make \
    /usr/local/share/mklib/make \
    /usr/local/lib/mklib/make \
    /usr/share/mklib/make \
    /usr/lib/mklib/make

MAKE_INCLUDE_MODULES ?=
MAKE_EXCLUDE_MODULES ?=

-include $(MAKE_REPO_CONFIG)

rwildcard = $(foreach entry,$(wildcard $(1)/*),\
    $(if $(wildcard $(entry)/.),\
        $(call rwildcard,$(entry),$(2)),\
        $(filter $(subst *,%,$(2)),$(entry))))

modules_in = $(sort $(call rwildcard,$(1),*.mk))

module_relative = $(patsubst $(1)/%,%,$(2))

MAKE_LOCAL_MODULES := $(filter-out $(MAKE_REPO_CONFIG),\
    $(call modules_in,$(MAKE_REPO_MODULE_DIR)))

MAKE_LOCAL_NAMES := $(foreach file,$(MAKE_LOCAL_MODULES),\
    $(call module_relative,$(MAKE_REPO_MODULE_DIR),$(file)))

MAKE_SEEN_MODULES := $(MAKE_LOCAL_NAMES) $(MAKE_EXCLUDE_MODULES)

define select_shared_modules
$(foreach file,$(call modules_in,$(1)),\
    $(if $(filter $(MAKE_SEEN_MODULES),$(call module_relative,$(1),$(file))),,\
        $(if $(strip $(MAKE_INCLUDE_MODULES)),\
            $(if $(filter $(MAKE_INCLUDE_MODULES),$(call module_relative,$(1),$(file))),\
                $(eval MAKE_SEEN_MODULES += $(call module_relative,$(1),$(file)))$(file)),\
            $(eval MAKE_SEEN_MODULES += $(call module_relative,$(1),$(file)))$(file))))
endef

MAKE_GLOBAL_MODULES := $(strip $(foreach dir,$(MAKE_LIBRARY_DIRS),\
    $(call select_shared_modules,$(dir))))

include $(MAKE_GLOBAL_MODULES)
include $(MAKE_LOCAL_MODULES)