PLUGIN_FILE := plugin.php
COMPOSER_FILE := composer.json
README_FILE := README.md
VERSION_CONST := DDLM_VERSION

CURRENT_VERSION := $(shell grep -oE '[0-9]+\.[0-9]+\.[0-9]+' $(PLUGIN_FILE) | head -1)

MAJOR := $(word 1,$(subst ., ,$(CURRENT_VERSION)))
MINOR := $(word 2,$(subst ., ,$(CURRENT_VERSION)))
PATCH := $(word 3,$(subst ., ,$(CURRENT_VERSION)))

NEW_PATCH := $(MAJOR).$(MINOR).$(shell expr $(PATCH) + 1)
NEW_MINOR := $(MAJOR).$(shell expr $(MINOR) + 1).0
NEW_MAJOR := $(shell expr $(MAJOR) + 1).0.0

define do_bump
	@[ -n "$(DESC)" ] || { echo "Error: DESC is required. Usage: make $(1) DESC=\"description\""; exit 1; }
	sed -i '' "s/\* Version: $(CURRENT_VERSION)/\* Version: $(2)/" $(PLUGIN_FILE)
	sed -i '' "s/$(VERSION_CONST)', '$(CURRENT_VERSION)'/$(VERSION_CONST)', '$(2)'/" $(PLUGIN_FILE)
	if [ -f $(COMPOSER_FILE) ] && grep -q '"version"' $(COMPOSER_FILE); then \
		sed -i '' "s/\"version\": \"$(CURRENT_VERSION)\"/\"version\": \"$(2)\"/" $(COMPOSER_FILE); \
	fi
	awk -v ver="$(2)" -v desc="$(DESC)" '/^## Changelog/{print; print ""; print "### " ver; print ""; print "- " desc; print ""; skip=1; next} skip && /^$$/{skip=0; next} {skip=0} 1' $(README_FILE) > $(README_FILE).tmp && mv $(README_FILE).tmp $(README_FILE)
	git add $(PLUGIN_FILE) $(COMPOSER_FILE) $(README_FILE)
	git commit -m "v$(2) - $(DESC)"
	git tag $(2)
	git push && git push --tags
	@echo "Done. Committed, tagged and pushed $(2)."
endef

.PHONY: info patch minor major

info:
	@echo "Current version: $(CURRENT_VERSION)"

patch:
	$(call do_bump,patch,$(NEW_PATCH))

minor:
	$(call do_bump,minor,$(NEW_MINOR))

major:
	$(call do_bump,major,$(NEW_MAJOR))
