ifeq "$(CONFIG_DASHARO_EC)" "y"

modules-y += dasharo-ec

dasharo-ec_repo := https://github.com/Dasharo/ec
dasharo-ec_commit_hash := d198b641195e60e13afc17be9464e4f402d1c2fa

# Strip UNTESTED_/EOL_ prefix for board model mapping
_DASHARO_EC_BOARD := $(patsubst EOL_%,%,$(patsubst UNTESTED_%,%,$(BOARD)))

# Map BOARD to the EC board model
ifeq "$(_DASHARO_EC_BOARD)" "novacustom-v540tu"
	DASHARO_EC_BOARD_MODEL := v540tu
else ifeq "$(_DASHARO_EC_BOARD)" "novacustom-v560tu"
	DASHARO_EC_BOARD_MODEL := v560tu
else ifeq "$(_DASHARO_EC_BOARD)" "novacustom-nv4x_adl"
	DASHARO_EC_BOARD_MODEL := nv4x_adl
else ifeq "$(_DASHARO_EC_BOARD)" "nitropad-ns50"
	DASHARO_EC_BOARD_MODEL := ns5x_adl
else
	$(error "$(BOARD): no Dasharo EC board model mapping defined")
endif

dasharo-ec_version := $(dasharo-ec_commit_hash)
dasharo-ec_base_dir := dasharo-ec-$(dasharo-ec_version)-$(BOARD)
dasharo-ec_dir := dasharo-ec-$(dasharo-ec_version)-$(BOARD)

# ec.rom is copied to a stable path by the explicit rule below
dasharo-ec_output := ec.rom

# No-op configure: submodules are handled by the EC Makefile's canary rule
# for git repos
dasharo-ec_configure :=

# Build the EC firmware: only pass make arguments; post-build steps are
# handled by the explicit rule below.
dasharo-ec_target := BOARD=novacustom/$(DASHARO_EC_BOARD_MODEL)

# Copy ec.rom from the dynamic build path to a stable location and pad to
# 128KB as required by coreboot. Runs after the module make completes.
$(build)/$(dasharo-ec_dir)/ec.rom: $(build)/$(dasharo-ec_dir)/.build
	cp $(build)/$(dasharo-ec_dir)/build/novacustom/$(DASHARO_EC_BOARD_MODEL)/*/ec.rom $@
	truncate --size=128KiB $@

# Copy ec.rom into the coreboot source tree before coreboot builds.
# coreboot_base_dir (coreboot-dasharo) is shared between v540tu and v560tu, so
# a plain timestamp-based rule is racy: whichever board built last wins the mtime
# race and the other board silently keeps the wrong binary.  Adding FORCE makes the
# recipe always run so we can do a content check; the actual cp (and the mtime
# update that triggers downstream rebuilds) only happens when the content differs.
$(build)/$(coreboot_base_dir)/ec.rom: $(build)/$(dasharo-ec_dir)/ec.rom FORCE
	@if ! cmp -s "$(build)/$(dasharo-ec_dir)/ec.rom" "$@" 2>/dev/null; then \
		echo "$(DATE) COPY $(DASHARO_EC_BOARD_MODEL) ec.rom -> coreboot"; \
		cp "$(build)/$(dasharo-ec_dir)/ec.rom" "$@"; \
	fi

# Ensure coreboot's configure step depends on ec.rom being present
$(build)/$(coreboot_dir)/.configured: $(build)/$(coreboot_base_dir)/ec.rom

endif
