FACTORIO := $(HOME)/.factorio

MOD := $(shell jq -j .name info.json)
# because  `bump` updates info.json's .version,
# and I want `make bump install` to work:
VER := $$(jq -j .version info.json)

.PHONY: install install-archive archive bump setup

install: setup
	rm -f $(FACTORIO)/mods/$(MOD)_[0-9]*; \
	ln -s `pwd -P` $(FACTORIO)/mods/$(MOD)_$(VER)

install-archive: archive
	rm -f $(FACTORIO)/mods/$(MOD)_[0-9]*; \
	ln $(MOD)_$(VER).zip $(FACTORIO)/mods

archive: setup
	@git diff-index --quiet @ || echo note: HEAD is dirty
	@if _=`git rev-parse -q --verify :utils`; then \
		git -C utils diff-index --quiet $$(git rev-parse :utils) || echo note: utils is dirty; \
		fi
	MODVER=$(MOD)_$(VER); \
	git archive @ --prefix=$$MODVER/ -o $$MODVER.zip && \
	if _=`git rev-parse -q --verify :utils`; then \
		git -C utils archive --prefix=$$MODVER/utils/ -o $$PWD/.append.zip $$(git rev-parse :utils) \
		&& zipmerge $$MODVER.zip .append.zip && rm .append.zip; \
	fi

bump:
	IFS=. read major minor patch <<<`jq -r .version info.json`; \
		jq .version=\"$$major.$$minor.$$((++patch))\" info.json > newinfo.json
	mv newinfo.json info.json

setup:	utils/.git ;

%/.git:
	@if _=`git rev-parse -q --verify :$(@D)`; then \
		git config submodule.$(@D).active true \
		&& git config submodule.$(@D).url ./ \
		&& git clone -sn . $(@D) \
		&& git submodule --quiet absorbgitdirs $(@D) \
		&& git -C $(@D) checkout $$(git rev-parse :$(@D)); \
	fi
