#
# Partition table
#
# The partition table is not a real component that gets linked into
# the project. Instead, it is a standalone project to generate
# the partition table binary as part of the build process. This
# binary is then added to the list of files for esptool.py to flash.
#
.PHONY: partition_table partition_table-flash partition_table-clean

# NB: gen_esp32part.py lives in the sdk/bin/ dir not component dir
GEN_ESP32PART := $(PYTHON) $(IDF_PATH)/bin/gen_esp32part.py -q

# Path to partition CSV file is relative to project path for custom
# partition CSV files, but relative to component dir otherwise.$
PARTITION_TABLE_ROOT := $(call dequote,$(if $(CONFIG_PARTITION_TABLE_CUSTOM),$(PROJECT_PATH),$(COMPONENT_PATH)))
PARTITION_TABLE_CSV_PATH := $(call dequote,$(abspath $(PARTITION_TABLE_ROOT)/$(subst $(quote),,$(CONFIG_PARTITION_TABLE_FILENAME))))

PARTITION_TABLE_BIN := $(BUILD_DIR_BASE)/$(notdir $(PARTITION_TABLE_CSV_PATH:.csv=.bin))

$(PARTITION_TABLE_BIN): $(PARTITION_TABLE_CSV_PATH)
	@echo "Building partitions from $(PARTITION_TABLE_CSV_PATH)..."
	$(Q) $(GEN_ESP32PART) $< $@

all_binaries: $(PARTITION_TABLE_BIN)

PARTITION_TABLE_FLASH_CMD = $(ESPTOOLPY_SERIAL) write_flash 0x4000 $(PARTITION_TABLE_BIN)
ESPTOOL_ALL_FLASH_ARGS += 0x4000 $(PARTITION_TABLE_BIN)

partition_table: $(PARTITION_TABLE_BIN)
	@echo "Partition table binary generated. Contents:"
	@echo $(SEPARATOR)
	$(Q) $(GEN_ESP32PART) $<
	@echo $(SEPARATOR)
	@echo "Partition flashing command:"
	@echo "$(PARTITION_TABLE_FLASH_CMD)"

partition_table-flash: $(PARTITION_TABLE_BIN)
	@echo "Flashing partition table..."
	$(Q) $(PARTITION_TABLE_FLASH_CMD)

partition_table-clean:
	$(Q) rm -f $(PARTITION_TABLE_BIN)

clean: partition_table-clean
