###############################################################################
## FUNCTIONS
###############################################################################

###############################################################################
## Colored output
###############################################################################

# Enable colored output
ifeq ($(SONIC_CONFIG_ENABLE_COLORS),y)
ifeq ($(MAKE_TERMOUT),)
RED=\033[1;31m
PURPLE=\033[1;35m
CYAN=\033[1;36m
GREEN=\033[1;32m
GRAY=\033[0m
endif
endif

# Print red colored output
# call:
#       log_red message
log_red = echo -e "$(RED)$(1)$(GRAY)"

# Print purple colored output
# call:
#       log_purple message
log_purple = echo -e "$(PURPLE)$(1)$(GRAY)"

# Print blue colored output
# call:
#       log_blue message
log_blue = echo -e "$(CYAN)$(1)$(GRAY)"

# Print green colored output
# call:
#       log_green message
log_green = echo -e "$(GREEN)$(1)$(GRAY)"

###############################################################################
## Logging
###############################################################################

ifeq ($(SONIC_CONFIG_LOG_TO_FILES),y)
FLUSH_LOG = rm -f $@.log

LOG = &>> $(PROJECT_ROOT)/$@.log || { [ $$? -eq 0 ] || cat  $(PROJECT_ROOT)/$@.log ; false ; }
endif

###############################################################################
## Header and footer for each target
###############################################################################

# Print name of target being built
PRINT_TARGET = $(call log_purple,Executing rules for $@)

# Print name of target that finished build
PRINT_END_TARGET = $(call log_green,Finished $@)

# Dump targets taht current depends on
ifeq ($(SONIC_CONFIG_PRINT_DEPENDENCIES),y)
PRINT_DEPENDENCIES = $(call log_blue,Dependencies for $@ are $^)
endif

# Enable verbose mode
ifneq ($(SONIC_CONFIG_VERBOSE),y)
ENABLE_VERBOSE = @
endif

# header for each rule
define HEADER
$(ENABLE_VERBOSE)
$(PRINT_TARGET)
$(PRINT_DEPENDENCIES)
$(FLUSH_LOG)
endef

# footer for each rule
define FOOTER
$(PRINT_END_TARGET)
endef

###############################################################################
## Definition of derived target
###############################################################################

# call:
#     add_derived_package some_deb.deb, some_derived_deb
define add_derived_package
$(2)_DEPENDS += $(1)
$(2)_RDEPENDS += $($(1)_RDEPENDS)
$(2)_DERIVED_FROM = $(1)
$(1)_DERIVED_DEBS += $(2)
$(2)_URL = $($(1)_URL)
$(2)_SRC_PATH = $($(1)_SRC_PATH)
SONIC_DERIVED_DEBS += $(2)
endef

###############################################################################
## Utility functions
###############################################################################

expand = $(foreach d,$(1),$(call expand,$($(d)_$(2)),$(2))) $(1)