export CODEFRESH_CLI ?= codefresh
export CODEFRESH_CLI_SHARED_DIR ?= /data
export CF_API_URL ?= https://g.codefresh.io

PIPELINES ?= $(call pipelines,$(ACCOUNT))

define pipelines
	$(value $(shell echo $(1)_PIPELINES | tr 'a-z' 'A-Z'))
endef

define codefresh-use-context
	@$(CODEFRESH_CLI) auth use-context $(PROJECT)-$(1)
endef

## Authentificate on codefresh account
codefresh/sync/auth/%: codefresh/sync/deps
	$(call assert-set,CF_API_KEY)
	$(call assert-set,CF_API_URL)
	$(call assert-set,PROJECT)
	@$(CODEFRESH_CLI) auth create-context $(PROJECT)-$(subst codefresh/sync/auth/,,$@) --api-key $(CF_API_KEY) --url $(CF_API_URL)


## Install dependencies for codefresh sync
codefresh/sync/deps: packages/install/gomplate packages/install/yq packages/install/codefresh
	@exit 0

## Codefresh pipelines sync - Show changes
codefresh/sync/diff: codefresh/sync
	@exit 0;

## Codefresh pipelines sync - Apply the changes
codefresh/sync/apply:
	@$(MAKE) -s codefresh/sync APPLY=true

codefresh/sync: codefresh/sync/deps
	$(call assert-set,REPOSITORIES)
	@for repo in $(REPOSITORIES) ; do \
		echo ">>>> Processing $${repo} repo"; \
		for account in $(ACCOUNTS) ; do \
			$(MAKE) -s codefresh/sync/pipelines ACCOUNT=$$account REPOSITORY=$$repo; \
		done; \
		echo $(shell printf -- '=%.0s' {1..80}); \
	done

codefresh/sync/pipelines:
	$(call assert-set,REPOSITORY)
	$(call assert-set,ACCOUNT)
	$(call codefresh-use-context,$(ACCOUNT))
	@for pipeline in $(PIPELINES); do \
		PIPELINE=$$pipeline $(BUILD_HARNESS_PATH)/bin/codefresh-sync.sh; \
	done
