modules-$(CONFIG_LINUXBOOT) += linuxboot

linuxboot_version := git
linuxboot_repo := https://github.com/osresearch/linuxboot
linuxboot_base_dir := linuxboot-$(linuxboot_version)

# linuxboot builds are specialized on a per-target basis.
# They can be specialized by defining $(CONFIG_LINUXBOOT_BOARD)
# otherwise it is assumed that it will have the same name
# as the Heads BOARD.
linuxboot_board := $(or $(CONFIG_LINUXBOOT_BOARD),$(BOARD))
linuxboot_dir := linuxboot-$(linuxboot_version)/build/$(linuxboot_board)

linuxboot_configure := \
	echo >&2 "Pre-building edk2" ; \
	$(MAKE) \
		-C $(build)/$(linuxboot_base_dir) \
		BOARD=$(linuxboot_board) \
		edk2.force \
	|| exit 1 ; \
	if [ "$(linuxboot_board)" = "qemu" ]; then \
		echo >&2 "Pre-building edk2 OVMF" ; \
		( cd $(build)/$(linuxboot_base_dir)/edk2/OvmfPkg ; \
		./build.sh -n $(CPUS) \
		) || exit 1 ; \
	fi ; \
	touch .config ; \

ifdef CUSTOM
	CUSTOMPWD=$(pwd)/$(CUSTOM)
endif

linuxboot_target := \
	-C $(build)/$(linuxboot_base_dir) \
	BOARD=$(linuxboot_board) \
	KERNEL=$(build)/$(BOARD)/bzImage \
	INITRD=$(build)/$(BOARD)/initrd.cpio.xz \
	CUSTOM=$(CUSTOMPWD) \
	CROSS=$(CROSS) \
	$(if $(CONFIG_LINUXBOOT_ROM), ROM=$(pwd)/$(CONFIG_LINUXBOOT_ROM)) \
	all

#
# Most mainboards will define a ROM file that contains the vendor ROM
# for the image.  Provide a reasonable error if the ROM file doesn't exist.
#
ifneq "$(CONFIG_LINUXBOOT_ROM)" ""
ifneq "y" "$(shell [ -r '$(CONFIG_LINUXBOOT_ROM)' ] && echo y)"
$(error $(CONFIG_LINUXBOOT_ROM): you must provide a ROM file)
endif

endif


# The output file from the LinuxBoot build is a full ROM
# ready to flash onto the mainboard.  There might be partial
# firmware volumes as well, but that depends on the board
# so this only retrieves the final one
linuxboot_output := build/$(linuxboot_board)/linuxboot.rom
linuxboot_rom := $(build)/$(linuxboot_dir)/$(linuxboot_output)

ifneq ($(CONFIG_LINUXBOOT),)
$(build)/$(BOARD)/$(LB_OUTPUT_FILE): $(build)/$(linuxboot_dir)/.build
	$(call do-copy,$(dir $<)linuxboot.rom,$@)
	@touch $@
endif

# Also force a rebuild if any of the input files are updated
$(build)/$(linuxboot_dir)/.build: \
	$(CONFIG_LINUXBOOT_ROM) \
	$(build)/$(BOARD)/bzImage \
	$(build)/$(BOARD)/initrd.cpio.xz \


linuxboot.run: $(build)/$(BOARD)/$(LB_OUTPUT_FILE)
	$(MAKE) -C $(build)/$(linuxboot_base_dir)  \
		BOARD:=$(linuxboot_board) \
		KERNEL=$(build)/$(BOARD)/bzImage \
		INITRD=$(build)/$(BOARD)/initrd.cpio.xz \
		CUSTOM=$(CUSTOMPWD) \
		run