# defaults, override with caution
IMAGE_NAME = carsharing/emergency_admin
DOCKER_IMAGE_NAME = registry.yandex.net/$(IMAGE_NAME)
VERSION = `node -e "console.log(require('./package.json').version)"`
BRANCH = `git rev-parse --abbrev-ref HEAD`
DEPLOY_TARGET=production # any value that isn't "production" will be interpreted as "branch"
REVISION=patch
BACKEND_CLUSTER=testing

semver:
	npm --no-git-tag-version version $(REVISION) -f

# | tee <file>.log means that stdout and stderr of the scripts should be copied to <file>.log
docker-build:
	 ./build_release.sh -d $(DEPLOY_TARGET) -b $(BACKEND_CLUSTER) && \
		./build_docker.sh -t $(TAG) -d $(DEPLOY_TARGET) -p $(PREVIOUS_RELEASE) | tee ./build_docker.log

docker-publish:
	docker push $(DOCKER_PATH):$(VERSION)

# Usage: make build_first_release DEPLOY_TARGET=production
build_first_release:
	./build_release.sh -d $(DEPLOY_TARGET)

restore-files-mdate:
	source ~/.bash_profile && source ~/.bashrc && git-restore-mtime

create-release:
	source ~/.bash_profile && source ~/.bashrc && ya tool dctl release docker -t $(VERSION) $(IMAGE_NAME)

# Usage: make publish (REVISION=<patch | minor | major etc>)
# To publish to (prestable).carsharing.yandex-team.ru
# LATEST_RELEASE=<last modified folder in releases> , PREVIOUS_RELEASE=<second to last modified folder in releases>
# Accepts custom PREVIOUS_RELEASE
# Don't use on branches!!!
publish:
	 make restore-files-mdate && make REVISION=$(REVISION) semver && \
 		make DEPLOY_TARGET=production BACKEND_CLUSTER=$(BACKEND_CLUSTER) PREVIOUS_RELEASE=$(PREVIOUS_RELEASE) TAG=$(DOCKER_PATH):$(VERSION) docker-build && \
    	make VERSION=$(VERSION) docker-publish && make create-release

# Usage: make build_docker_image (REVISION=<patch | minor | major etc>)
# To build a docker image without publishing it to registry
# LATEST_RELEASE=<last modified folder in releases> , PREVIOUS_RELEASE=<second to last modified folder in releases>
# Accepts custom PREVIOUS_RELEASE
build_docker_image:
	make restore-files-mdate && make REVISION=$(REVISION) semver && \
 		make DEPLOY_TARGET=production BACKEND_CLUSTER=$(BACKEND_CLUSTER) PREVIOUS_RELEASE=$(PREVIOUS_RELEASE) TAG=$(DOCKER_PATH):$(VERSION) docker-build

# Usage: make publish_branch (BRANCH=<name>)
# To publish current branch to testing.carsharing.yandex-team.ru
# LATEST_RELEASE=dist, PREVIOUS_RELEASE=<last master version>
# Accepts custom PREVIOUS_RELEASE
# Sometimes name of git branch can be unsuitable for a docker tag  In this case, set BRANCH manually
publish_branch:
	make restore-files-mdate && make REVISION=prerelease semver && \
		make DEPLOY_TARGET=branch BACKEND_CLUSTER=$(BACKEND_CLUSTER) docker-build PREVIOUS_RELEASE=$(PREVIOUS_RELEASE) TAG=$(DOCKER_PATH):$(BRANCH)_$(VERSION) && \
		make VERSION=$(BRANCH)_$(VERSION) docker-publish && make VERSION=$(BRANCH)_$(VERSION) create-release
