COMPOSER_FILE := composer.json
README_FILE := README.md

CURRENT_VERSION := $(shell grep -m1 -oE '"version": *"[0-9]+\.[0-9]+\.[0-9]+"' $(COMPOSER_FILE) | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')

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)\"/" $(COMPOSER_FILE)
	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 $(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))
