# Makefile variables set automatically
plugin_package_json=plugin.json
plugin_id=`cat ${plugin_package_json} | python3 -c "import sys, json; print(str(json.load(sys.stdin)['id']).replace('/',''))"`
ifeq ($(origin plugin_version), undefined)
    plugin_version=$(shell cat $(plugin_package_json) | python3 -c "import sys, json; print(str(json.load(sys.stdin)['version']).replace('/',''))")
    $(info No argument plugin_version has been passed, we will use current version: $(plugin_version))
	fe-build-required=false
else
    plugin_version=$(plugin_version)
    $(info Using provided plugin_version: $(plugin_version))
	fe-build-required=true
endif

archive_file_name="dss-plugin-${plugin_id}-${plugin_version}.zip"
remote_url=`git config --get remote.origin.url`
frontend_package_json=resource/frontend/package.json

# Print a message based on whether the branch argument is passed or not
ifeq ($(origin branch), undefined)
    branch = $(shell git rev-parse --abbrev-ref HEAD)
    $(info No argument branch has been passed, we will use current branch: $(branch))
else
    $(info Using branch: $(branch))
endif

last_commit_id=`git rev-parse HEAD`

.DEFAULT_GOAL := plugin

help:
	@echo "Available targets and options:"
	@echo ""
	@echo "Steps:"
	@echo "  plugin          		Build a version of the plugin."
	@echo "                  		Usage: make plugin [plugin_version=VERSION] [branch=BRANCH] [add_tag=true]"
	@echo "                  		- plugin_version: Specify the plugin version (default: current version from plugin.json)."
	@echo "                  		- add_tag: Specify if you want to add a git tag after building (default: false)."
	@echo "                  		- branch: Specify the branch to build from (default: current branch)."
	@echo ""
	@echo "  dev             		Build plugin version based on local branch."
	@echo "                  		Usage: make dev"

plugin: dist-clean update-package-version-in-git-and-build
	@echo "\n\033[36m[START] 📦 Archiving plugin to dist/ folder...\033[0m"
	@cat ${plugin_package_json} | json_pp > /dev/null
	@mkdir dist
	@echo "{\"remote_url\":\"${remote_url}\",\"branch\":\"${branch}\",\"last_commit_id\":\"${last_commit_id}\"}" > release_info.json
	@ORIGINAL_COMMIT=$$(git rev-parse HEAD); echo "Current commit: $$ORIGINAL_COMMIT";
	@echo "\n📦 Creating archive..."
	@cd temp_repo && git archive -v -9 --format zip -o ../dist/${archive_file_name} HEAD
	@if [[ -d tests ]]; then \
		zip --delete dist/${archive_file_name} "tests/*"; \
	fi
	@zip -u dist/${archive_file_name} release_info.json
	@if [ "$(add_tag)" = "true" ]; then \
        $(MAKE) tagged-release; \
	fi
	@rm release_info.json
	@rm -rf temp_repo
	@echo "\033[32m[SUCCESS] Archiving plugin to dist/ folder:\033[0m"
	@echo "\n\n                       🌟💎Done!💎🌟\n"
	@echo "\n\033[32m🔔 Don't forget to pull any changes from the remote branch! 🔔\n\033[0m"; \

dev: dist-clean
	@echo "\033[36m[START] 📦 Archiving plugin to dist/ folder... (dev mode)\033[0m"
	@cat plugin.json | json_pp > /dev/null
	@mkdir dist
	@zip -v -9 dist/${archive_file_name} -r . --exclude "tests/*" "env/*" ".git/*" ".pytest_cache/*" ".idea/*" "dist/*"
	@echo "\033[32m[SUCCESS] Archiving plugin to dist/ folder: Done!\033[0m"

check-branch-is-on-remote:
	@echo "\n🔄 Fetching latest from remote..."
	@git fetch origin $(branch)
	@echo "🔄 Checking if local and remote HEADs match for branch '$(branch)'..."
	@LOCAL_COMMIT=$$(git rev-parse $(branch)); \
	REMOTE_COMMIT=$$(git rev-parse origin/$(branch)); \
	if [ "$$LOCAL_COMMIT" = "$$REMOTE_COMMIT" ]; then \
	    echo "\033[32m✅ Local and remote branches are in sync.\033[0m"; \
	else \
	    echo "\033[33m🚨 Warning: Local and remote branches are different!\033[0m"; \
	fi

update-package-version-in-git-and-build: check-branch-is-on-remote
	@echo ""
	@echo "\033[36m[START] 🔄 Updating package.json version with plugin version ${plugin_version} in git\033[0m"
	@echo "🧹 Cleaning temp_repo folder..."
	@rm -rf temp_repo
	@echo "🔄 Cloning ${branch} branch from ${remote_url} into temporary repository..."
	@git clone --branch ${branch} --single-branch ${remote_url} temp_repo
	@cd temp_repo && $(MAKE) update-plugin-json-version
	@cd temp_repo && $(MAKE) update-frontend-version	
	@cd temp_repo && git add ${frontend_package_json} ${plugin_package_json}
	@if [ "$(fe-build-required)" = "false" ]; then \
		echo "\n⏭️ Skipping frontend build "; \
	else \
		echo "\n🛠️ Building frontend..."; \
		cd temp_repo/resource/frontend && rm -f yarn.lock && yarn install && yarn build || exit 1; \
	fi
	@echo "\n🔄 Adding resource/dist to git..."
	@cd temp_repo && git add resource/dist || echo "No changes were made"
	@echo "🔄 Committing package.json version update and frontend build..."
	@cd temp_repo && git commit -m "build: bump plugin version (${plugin_version}) & build frontend" || echo "Nothing to commit"
	@echo "🔄 Pushing changes to ${branch} branch..."
	@cd temp_repo && git push origin ${branch} || echo "Nothing to push"
	@if [ "$(add_tag)" = "true" ]; then \
		$(MAKE) add-git-tag; \
	fi
	@echo "\033[32m[SUCCESS] Updating package.json version with plugin version ${plugin_version} in git: Done!\033[0m"

update-frontend-version:
	@echo "\n🚀 Bumping frontend ${frontend_package_json} with plugin version ${plugin_version}"
	@cp $(frontend_package_json) $(frontend_package_json).bak
	@sed "s/\"version\": \".*\"/\"version\": \"${plugin_version}\"/" $(frontend_package_json).bak > $(frontend_package_json)
	@rm $(frontend_package_json).bak

update-plugin-json-version:
	@echo "\n🚀 Bumping plugin ${plugin_package_json} with new version ${plugin_version}"
	@current_plugin_version=`cat ${plugin_package_json} | python3 -c "import sys, json; print(str(json.load(sys.stdin)['version']))"`
	@if [ "${plugin_version}" != "$$current_plugin_version" ]; then \
		cp ${plugin_package_json} ${plugin_package_json}.bak; \
		echo "Updating ${plugin_package_json} with new version ${plugin_version}"; \
		sed "s/\"version\": \".*\"/\"version\": \"${plugin_version}\"/" ${plugin_package_json}.bak > ${plugin_package_json}; \
		rm ${plugin_package_json}.bak; \
	else \
		echo "${plugin_package_json} is already at version ${plugin_version}"; \
	fi

add-git-tag:
	@echo "\n\033[36m[START] 🔖 Adding tag v${plugin_version} to main repository\033[0m"
	@git tag -a "v${plugin_version}" -m "Tagging version ${plugin_version}"
	@git push origin "v${plugin_version}"

tagged-release:
	@echo "\n\033[36m[START] 🔖 Creating GitHub release and attaching archive...\033[0m"
	@gh release create "v${plugin_version}" dist/${archive_file_name} \
	    --title "Version ${plugin_version}" \
		--generate-notes

dist-clean:
	@echo "\n🧹 Cleaning dist folder..."
	rm -rf dist
