.ONESHELL:
.DEFAULT_GOAL := plugin

# Makefile variables set automatically
plugin_id=`cat plugin.json | python3 -c "import sys, json; print(str(json.load(sys.stdin)['id']).replace('/',''))"`
plugin_version=`cat plugin.json | python3 -c "import sys, json; print(str(json.load(sys.stdin)['version']).replace('/',''))"`
archive_file_name="dss-plugin-${plugin_id}-${plugin_version}.zip"
remote_url=`git config --get remote.origin.url`
last_commit_id=`git rev-parse HEAD`

ROOT_DIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
VENV_EXISTS := $(shell [ -d "${ROOT_DIR}/.venv" ] && echo "true" || echo "false")

help:
	@echo "Makefile commands:"
	@echo "  setup                    - Create the virtual environment for VSCode and install its dependencies"
	@echo "  clean-setup              - Delete the virtual environment if it exists"
	@echo "  dev                      - Set up the development environment and open VSCode"
	@echo "  plugin                   - Build the slack integration plugin"
	@echo "  install                  - Build and install the slack integration plugin - requires setting the DIP_HOME environment variable"

plugin: dist-clean
	@echo "[START] Archiving plugin to dist/ folder..."
	@cat plugin.json | json_pp > /dev/null
	@mkdir dist
	@echo "{\"remote_url\":\"${remote_url}\",\"last_commit_id\":\"${last_commit_id}\"}" > release_info.json
	@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
	@rm release_info.json
	@echo "[SUCCESS] Archiving plugin to dist/ folder: Done!"

install: plugin
	python3 install_plugin.py

install-symlink: plugin
	python3 install_plugin.py --symlink

setup:
ifeq ($(VENV_EXISTS), true)
	@echo "Virtual environment already exists."
else
	@echo "Creating virtual environment."
	python3 -m venv .venv
	. .venv/bin/activate

	@echo "Installing environment dependencies."

	@echo "Installing internal dataiku package."
	pip install https://staging-design.qa.managedinstances.dkucloud-dev.com/public/packages/dataiku-internal-client.tar.gz

	@echo "Installing public dataikuapi package."
	pip install dataiku-api-client \

	@echo "Installing plugin code environment requirements."
	pip install -r ${ROOT_DIR}/code-env/python/spec/requirements.txt

	@echo "Virtual environment created and dependencies installed."
endif

clean-setup:
ifeq ($(VENV_EXISTS), true)
	@echo "Deleting virtual environment."
	rm -rf .venv
	@echo "Virtual environment deleted."
else
	@echo "No virtual environment to delete."
endif

dev: setup
	code ${ROOT_DIR}

dist-clean:
	rm -rf dist
