## 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

GITEA_URL       := https://git.tuxtech.fr
GITEA_OWNER     := tuxgyver
GITEA_REPO_NAME := DataControl
GITEA_TOKEN     ?= $(shell sed -n 's/^giteaToken=//p' gitea-token.properties 2>/dev/null | tr -d '[:space:]')

.DEFAULT_GOAL := help
.PHONY: help build release install push version-bump changelog clean tag _check-token _check-apk publish deploy

BOLD    := \033[1m
DIM     := \033[2m
CYAN    := \033[36m
GREEN   := \033[32m
YELLOW  := \033[33m
RESET   := \033[0m

help:
	@printf "\n"
	@printf "  $(BOLD)$(CYAN)DataControl$(RESET) $(DIM)— pare-feu de données mobiles et contrôle parental Android $(RESET)$(DIM)(v$(VERSION_NAME), build $(VERSION_CODE))$(RESET)\n"
	@printf "\n"
	@printf "  $(BOLD)🔨 Build & installation$(RESET)\n"
	@printf "    $(GREEN)make build$(RESET)               🔨  Construire l'APK debug\n"
	@printf "    $(GREEN)make release$(RESET)             📱  Construire l'APK release et le copier à la racine\n"
	@printf "    $(GREEN)make install$(RESET)             📲  Installer l'APK debug sur l'appareil connecté\n"
	@printf "\n"
	@printf "  $(BOLD)🚀 Versions & publication$(RESET)\n"
	@printf "    $(GREEN)make version-bump$(RESET)        🔖  Incrémenter versionCode et le patch de versionName\n"
	@printf "    $(GREEN)make changelog$(RESET)           📝  Ajouter au CHANGELOG les commits depuis le dernier tag\n"
	@printf "    $(GREEN)make push$(RESET)                📤  Commit, tag et push de la version courante\n"
	@printf "    $(GREEN)make tag$(RESET)                 📌  Créer et pousser le tag git de la version courante\n"
	@printf "    $(GREEN)make publish$(RESET)             🚀  Publier l'APK signé en Release Gitea (idempotent)\n"
	@printf "    $(GREEN)make deploy$(RESET)              🚢  Construire l'APK release puis le publier\n"
	@printf "\n"
	@printf "  $(BOLD)🧹 Nettoyage$(RESET)\n"
	@printf "    $(GREEN)make clean$(RESET)               🧽  Supprimer les artefacts de build et les APK racine\n"
	@printf "\n"

build:
	@printf "$(YELLOW)🔨 Construction de l'APK debug...$(RESET)\n"
	$(GRADLEW) assembleDebug
	@echo "[BUILD] Done: $(APK_DEBUG)"

release:
	@printf "$(YELLOW)📱 Construction de l'APK release v$(VERSION_NAME) (build $(VERSION_CODE))...$(RESET)\n"
	$(GRADLEW) assembleRelease
	@cp $(APK_RELEASE) $(OUTPUT_APK)
	@echo "[RELEASE] Done: $(OUTPUT_APK)"

install:
	@printf "$(YELLOW)📲 Installation de l'APK debug...$(RESET)\n"
	$(GRADLEW) installDebug
	@echo "[INSTALL] Done."

push:
	@printf "$(YELLOW)📤 Commit et push de v$(VERSION_NAME)...$(RESET)\n"
	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."

tag:
	@printf "$(YELLOW)📌 Tag git v$(VERSION_NAME)...$(RESET)\n"
	@if git rev-parse "v$(VERSION_NAME)" >/dev/null 2>&1; then \
	  echo "Tag v$(VERSION_NAME) already exists, skipping"; \
	else \
	  git diff --quiet || { echo "Working tree not clean — commit first (version.properties, CHANGELOG.md, …)"; exit 1; }; \
	  echo "Tag: v$(VERSION_NAME)"; \
	  git tag -a "v$(VERSION_NAME)" -m "Release v$(VERSION_NAME)"; \
	fi
	@git push origin "v$(VERSION_NAME)"
	@echo "Tag v$(VERSION_NAME) pushed"

_check-token:
	@test -n "$(GITEA_TOKEN)" || \
	  (echo "GITEA_TOKEN missing. Create gitea-token.properties (giteaToken=…) or export GITEA_TOKEN." && exit 1)

_check-apk:
	@test -f $(OUTPUT_APK) || \
	  (echo "$(OUTPUT_APK) not found — run 'make release' first." && exit 1)
	@test $(OUTPUT_APK) -nt version.properties || \
	  (echo "$(OUTPUT_APK) is older than version.properties — rerun 'make release'." && exit 1)

publish: _check-apk _check-token tag
	@printf "$(YELLOW)🚀 Publication de la release Gitea v$(VERSION_NAME)...$(RESET)\n"
	@EXISTING=$$(curl -s -H "Authorization: token $(GITEA_TOKEN)" \
	  "$(GITEA_URL)/api/v1/repos/$(GITEA_OWNER)/$(GITEA_REPO_NAME)/releases/tags/v$(VERSION_NAME)"); \
	 REL_ID=$$(printf '%s\n' "$$EXISTING" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['id'] if isinstance(d, dict) and 'id' in d else '')" 2>/dev/null); \
	 if [ -n "$$REL_ID" ]; then \
	   echo "Release v$(VERSION_NAME) already published (id=$$REL_ID), reusing"; \
	 else \
	   BODY=$$(awk -v ver="v$(VERSION_NAME)" '$$0 ~ "^## " ver {f=1; next} f && /^## /{exit} f{print}' CHANGELOG.md | \
	     python3 -c "import sys,json; print(json.dumps(sys.stdin.read().strip()))"); \
	   RESP=$$(curl -s -X POST \
	     -H "Authorization: token $(GITEA_TOKEN)" \
	     -H "Content-Type: application/json" \
	     "$(GITEA_URL)/api/v1/repos/$(GITEA_OWNER)/$(GITEA_REPO_NAME)/releases" \
	     -d "{\"tag_name\":\"v$(VERSION_NAME)\",\"name\":\"v$(VERSION_NAME)\",\"body\":$$BODY,\"draft\":false,\"prerelease\":false}"); \
	   REL_ID=$$(printf '%s\n' "$$RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null); \
	   if [ -z "$$REL_ID" ]; then echo "Error creating release: $$RESP"; exit 1; fi; \
	   echo "Release created (id=$$REL_ID)"; \
	 fi; \
	 OLD_ASSET=$$(curl -s -H "Authorization: token $(GITEA_TOKEN)" \
	   "$(GITEA_URL)/api/v1/repos/$(GITEA_OWNER)/$(GITEA_REPO_NAME)/releases/$$REL_ID" | \
	   python3 -c "import sys,json; a=[x['id'] for x in json.load(sys.stdin)['assets'] if x['name']=='$(OUTPUT_APK)']; print(a[0] if a else '')" 2>/dev/null); \
	 if [ -n "$$OLD_ASSET" ]; then \
	   curl -s -X DELETE -H "Authorization: token $(GITEA_TOKEN)" \
	     "$(GITEA_URL)/api/v1/repos/$(GITEA_OWNER)/$(GITEA_REPO_NAME)/releases/$$REL_ID/assets/$$OLD_ASSET" > /dev/null; \
	 fi; \
	 echo "Uploading $(OUTPUT_APK)…"; \
	 UPRESP=$$(curl -s -X POST -H "Authorization: token $(GITEA_TOKEN)" \
	   "$(GITEA_URL)/api/v1/repos/$(GITEA_OWNER)/$(GITEA_REPO_NAME)/releases/$$REL_ID/assets" \
	   -F "attachment=@$(OUTPUT_APK)"); \
	 UP_ID=$$(printf '%s\n' "$$UPRESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null); \
	 if [ -z "$$UP_ID" ]; then echo "Error uploading APK: $$UPRESP"; exit 1; fi; \
	 echo "APK uploaded"; \
	 echo ""; \
	 echo "$(GITEA_URL)/$(GITEA_OWNER)/$(GITEA_REPO_NAME)/releases/tag/v$(VERSION_NAME)"

deploy: release publish
	@printf "$(GREEN)🚢 Déploiement terminé.$(RESET)\n"

version-bump:
	@printf "$(YELLOW)🔖 Incrémentation de la version...$(RESET)\n"
	@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:
	@printf "$(YELLOW)📝 Génération du CHANGELOG depuis le dernier tag...$(RESET)\n"
	@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:
	@printf "$(YELLOW)🧽 Nettoyage des artefacts de build...$(RESET)\n"
	$(GRADLEW) clean
	@rm -f DataControl-*.apk
	@echo "[CLEAN] Done."
