$(shell git remote | grep -q -v origin && git remote add origin https://github.infra.cloudera.com/thunderhead/fluent-plugin-gcs | git fetch --tags origin)
TAG := $(shell git tag -l --contains HEAD || true)
COMMIT := $(shell git rev-parse --short HEAD)
SNAPSHOT_VERSION := $(shell head -1 VERSION | tr -d '\n'; echo '.pre') 
VERSION_FROM_TAG := $(TAG:v%=%)
ifeq ($(TAG),)
	VERSION_FROM_TAG := $(SNAPSHOT_VERSION)
endif

unit-test:
	bundler install --path ~/.gem
	ruby -Ilib:test test/all.rb

pre-args:
	(head -1 VERSION | tr -d '\n'; echo '.pre') > GEMSPEC_ARGS
	echo "https://repository.cloudera.com/artifactory/api/gems/cloudera-gems" >> GEMSPEC_ARGS
	echo $$(git rev-parse HEAD) >> GEMSPEC_ARGS

stable-args:
	(head -1 VERSION | tr -d '\n'; echo '') > GEMSPEC_ARGS
	echo "https://repository.cloudera.com/artifactory/api/gems/cloudera-gems" >> GEMSPEC_ARGS
	echo $$(git rev-parse HEAD) >> GEMSPEC_ARGS

tag:
	git tag "v$$(cat VERSION)" $(RELEASE_COMMIT)
	git push origin "v$$(cat VERSION)"

gem:
	rm -f fluent-plugin-gcs*.gem
	gem build fluent-plugin-gcs.gemspec

push-gem:
	gem push fluent-plugin-gcs-$$(head -1 GEMSPEC_ARGS).gem --host $$(sed -n '2p' GEMSPEC_ARGS)

check-release-commit:
	@echo "Check release commit if not empty: $(RELEASE_COMMIT)"
ifneq ($(RELEASE_COMMIT),)
	git checkout $(RELEASE_COMMIT)
endif

build: pre-args unit-test gem push-gem

local-build: pre-args unit-test gem

upload-s3-artifact:
	aws s3 cp fluent-plugin-gcs*.gem "s3://cloudera-service-delivery-cache/fluent-plugins/fluent-plugin-gcs/" --acl public-read

ifeq ($(VERSION_FROM_TAG), $(SNAPSHOT_VERSION))
release:
	echo "Not found any tags at HEAD. Current version is ${VERSION_FROM_TAG}. Skipping release process."
else
release: check-release-commit stable-args unit-test gem upload-s3-artifact push-gem
endif