## DataControl – Android Build & Release Makefile
## Author: JT-Tools by Johnny

VERSION_NAME := $(shell grep 'versionName' version.properties | cut -d= -f2 | tr -d ' ')
VERSION_CODE := $(shell grep 'versionCode' version.properties | cut -d= -f2 | tr -d ' ')

GRADLEW := ./gradlew
APK_RELEASE := app/build/outputs/apk/release/app-release.apk
APK_DEBUG := app/build/outputs/apk/debug/app-debug.apk
OUTPUT_APK := DataControl-$(VERSION_NAME).apk

.DEFAULT_GOAL := help

.PHONY: help build release install push version-bump changelog clean

## help: Show this help message
help:
	@echo "DataControl v$(VERSION_NAME) (build $(VERSION_CODE))"
	@echo ""
	@echo "Available targets:"
	@grep -E '^## [a-z]' Makefile | sed 's/## /  make /' | column -t -s ':'

## build: Build debug APK
build:
	@echo "[BUILD] Building debug APK..."
	$(GRADLEW) assembleDebug
	@echo "[BUILD] Done: $(APK_DEBUG)"

## release: Build release APK and copy to project root
release:
	@echo "[RELEASE] Building release APK for v$(VERSION_NAME) ($(VERSION_CODE))..."
	$(GRADLEW) assembleRelease
	@cp $(APK_RELEASE) $(OUTPUT_APK)
	@echo "[RELEASE] Done: $(OUTPUT_APK)"

## install: Install debug APK on connected device
install:
	@echo "[INSTALL] Installing debug APK..."
	$(GRADLEW) installDebug
	@echo "[INSTALL] Done."

## push: Git add, commit, tag and push (uses current version)
push:
	@echo "[PUSH] Committing and pushing v$(VERSION_NAME)..."
	git add -A
	git commit -m "Release v$(VERSION_NAME) (build $(VERSION_CODE))"
	git tag -a "v$(VERSION_NAME)" -m "Release v$(VERSION_NAME)"
	git push origin main
	git push origin "v$(VERSION_NAME)"
	@echo "[PUSH] Done."

## version-bump: Increment versionCode and update versionName patch
version-bump:
	@NEW_CODE=$$(( $(VERSION_CODE) + 1 )); \
	PATCH=$$(echo $(VERSION_NAME) | cut -d. -f3); \
	MAJOR=$$(echo $(VERSION_NAME) | cut -d. -f1); \
	MINOR=$$(echo $(VERSION_NAME) | cut -d. -f2); \
	NEW_PATCH=$$(( PATCH + 1 )); \
	NEW_VERSION="$${MAJOR}.$${MINOR}.$${NEW_PATCH}"; \
	sed -i "s/versionName=.*/versionName=$${NEW_VERSION}/" version.properties; \
	sed -i "s/versionCode=.*/versionCode=$${NEW_CODE}/" version.properties; \
	echo "[VERSION-BUMP] Bumped to $${NEW_VERSION} (build $${NEW_CODE})"

## changelog: Generate a changelog entry from git log since last tag
changelog:
	@echo "[CHANGELOG] Generating entries since last tag..."
	@LAST_TAG=$$(git describe --tags --abbrev=0 2>/dev/null || echo ""); \
	if [ -z "$$LAST_TAG" ]; then \
		git log --oneline --pretty=format:"- %s" >> CHANGELOG.md; \
	else \
		echo "" >> CHANGELOG.md; \
		echo "## v$(VERSION_NAME) – $$(date +%Y-%m-%d)" >> CHANGELOG.md; \
		git log $$LAST_TAG..HEAD --oneline --pretty=format:"- %s" >> CHANGELOG.md; \
	fi; \
	echo "[CHANGELOG] Done."

## clean: Clean build artifacts
clean:
	@echo "[CLEAN] Cleaning build artifacts..."
	$(GRADLEW) clean
	@rm -f DataControl-*.apk
	@echo "[CLEAN] Done."
