BUILDDIR ?= build

WGET ?= wget
PYTHON ?= python3

.PRECIOUS: $(BUILDDIR)/%.jar
.PRECIOUS: $(BUILDDIR)/%.jar.version
$(BUILDDIR)/%.jar:
	mkdir -p $(BUILDDIR)
	$(WGET) --tries=10 -O $@ $$($(PYTHON) tools/get_p2_url.py --write-version $@.version $*)
	touch $@

OUTPUTS := svd mx_mcu_db prog_db chip_db

all: $(OUTPUTS)

$(BUILDDIR)/%.dir: $(BUILDDIR)/%.jar
	mkdir -p $@
	rm -rf $@
	unzip -q -d $@ $<

.PHONY: update_svd
svd: $(BUILDDIR)/com.st.stm32cube.ide.mcu.productdb.debug.dir
	rm -rf $@
	mkdir -p $@
	cp $</resources/cmsis/STMicroelectronics_CMSIS_SVD/License.html $@/License.html
	cp $</resources/cmsis/STMicroelectronics_CMSIS_SVD/*.svd $@/
	cp $(BUILDDIR)/com.st.stm32cube.ide.mcu.productdb.debug.jar.version $@/source_file_versions.txt

.PHONY: update_xml
mx_mcu_db: $(BUILDDIR)/com.st.stm32cube.common.mx.dir
	rm -rf $@
	mkdir -p $@
	cp $</about.html $@/License.html
	cp -r $</db/mcu/* $@/
	cp $(BUILDDIR)/com.st.stm32cube.common.mx.jar.version $@/source_file_versions.txt

prog_db: $(BUILDDIR)/com.st.stm32cube.ide.mcu.externaltools.cubeprogrammer.linux64.dir
	rm -rf $@
	mkdir -p $@
	cp $</about.html $@/License.html
	cp $</tools/Data_Base/*.xml $@/
	cp $(BUILDDIR)/com.st.stm32cube.ide.mcu.externaltools.cubeprogrammer.linux64.jar.version $@/source_file_versions.txt

$(BUILDDIR)/STM32CubeMX.unpacked: build/com.st.stm32cube.common.mx.dir
	unzip -q -d $@ $</STM32CubeMX.jar -x '/*'

chip_db: $(BUILDDIR)/STM32CubeMX.unpacked
	rm -rf $@
	mkdir -p $@
	cp $</LICENSE.txt $@/
	cp $</devices/* $@/
	cp $(BUILDDIR)/com.st.stm32cube.common.mx.jar.version $@/source_file_versions.txt

.PHONY: clean
clean:
	rm -rf svd
	rm -rf mx_mcu_db
	rm -rf prog_db
	rm -rf chip_db
	rm -rf build

# The following file contains garbage data on the µC's memories.
#stm32targets.xml: $(BUILDDIR)/com.st.stm32cube.ide.mcu.productdb.dir
#	cp $</resources/board_def/$@ $@
#$(BUILDDIR)/com.st.stm32cube.ide.mcu.productdb.dir: