ifeq ("$(origin V)", "command line")
VERBOSE := $(V)
endif
ifneq ($(VERBOSE),1)
Q := @
endif

$(shell [ -L ".config" ] || ln -s "BuildRoot.config" ".config" >/dev/null 2>&1)

LOCAL_TARGETS := CopyConfig
LOCAL_TARGETS += SetupBuildRoot

lastword = $(word $(words $(1)),$(1))
makedir := $(dir $(call lastword,$(MAKEFILE_LIST)))

MAKEARGS := -C $(CURDIR)/src
MAKEARGS += O=$(CURDIR)

MAKEFLAGS += --no-print-directory

.PHONY: _all $(MAKECMDGOALS)

all := $(filter-out Makefile $(LOCAL_TARGETS),$(MAKECMDGOALS))

_all:
	$(Q)umask 0022 && $(MAKE) $(MAKEARGS) $(all)

Makefile:;

$(all): _all
	@:

%/: _all
	@:

# Local target runs directly
CopyConfig:
	test -f Linux.config && mv Linux.config Linux.config.old || true
	cp $$(find build/linux* -name .config) Linux.config
	test -f Busybox.config && mv Busybox.config Busybox.config.old || true
	cp $$(find build/busybox* -name .config) Busybox.config

	if ! $$(test -h .config); then \
		cp BuildRoot.config BuildRoot.config.old; \
		mv .config BuildRoot.config; \
		ln -s BuildRoot.config .config; \
		rm .config.old; \
	fi


SetupBuildRoot:
#	@BuildRootVer=2025.02.13;\#
	@BuildRootVer=$$(curl -s "https://buildroot.org/download.html" | tr '\n' ' ' | grep -oP '<tr>.*?</tr>' | grep -oP '<td>[^<]*' | sed -e 's/<td>//' -e 's/^[ \t]*//' |  grep -E '^[0-9]{4}\.[0-9]{2}(\.[0-9A-Za-z-]+)?$$' | tail -n1);\
	curl "https://buildroot.org/downloads/buildroot-$$BuildRootVer.tar.gz" -o /tmp/BuildRoot.tar.gz
	mkdir src
	tar -xzf /tmp/BuildRoot.tar.gz  --strip-components=1 -C ./src
	rm /tmp/BuildRoot.tar.gz
#	@bash $(CURDIR)/SetupDependesies.sh
