GRPCIO_VIRTUALENV=$(shell pwd)/grpc_python_venv
GENERATED_DIR=$(shell pwd)/generated_python
GENERATED_SUBDIR=_generated
BIGTABLE_DIR=$(shell pwd)/bigtable/google/cloud/bigtable/$(GENERATED_SUBDIR)
PROTOC_CMD=$(GRPCIO_VIRTUALENV)/bin/python -m grpc.tools.protoc
GOOGLEAPIS_PROTOS_DIR=$(shell pwd)/googleapis-pb

help:
	@echo 'Makefile for google-cloud-python Bigtable protos      '
	@echo '                                                      '
	@echo '   make generate        Generates the protobuf modules'
	@echo '   make clean           Clean generated files         '

generate:
	# Ensure we have a virtualenv w/ up-to-date grpcio/grpcio-tools
	[ -d $(GRPCIO_VIRTUALENV) ] || python2.7 -m virtualenv $(GRPCIO_VIRTUALENV)
	$(GRPCIO_VIRTUALENV)/bin/pip install --upgrade grpcio grpcio-tools
	# Retrieve git repos that have our *.proto files.
	[ -d googleapis-pb ] || git clone https://github.com/googleapis/googleapis googleapis-pb --depth=1
	cd googleapis-pb && git pull origin master
	# Make the directory where our *_pb2.py files will go.
	mkdir -p $(GENERATED_DIR)
	# Generate all *_pb2.py files that require gRPC.
	$(PROTOC_CMD) \
	    --proto_path=$(GOOGLEAPIS_PROTOS_DIR) \
	    --python_out=$(GENERATED_DIR) \
	    --grpc_python_out=$(GENERATED_DIR) \
	    $(GOOGLEAPIS_PROTOS_DIR)/google/bigtable/v2/bigtable.proto \
	    $(GOOGLEAPIS_PROTOS_DIR)/google/bigtable/admin/v2/bigtable_instance_admin.proto \
	    $(GOOGLEAPIS_PROTOS_DIR)/google/bigtable/admin/v2/bigtable_table_admin.proto
	# Generate all *_pb2.py files that do not require gRPC.
	$(PROTOC_CMD) \
	    --proto_path=$(GOOGLEAPIS_PROTOS_DIR) \
	    --python_out=$(GENERATED_DIR) \
	    $(GOOGLEAPIS_PROTOS_DIR)/google/bigtable/v2/data.proto \
	    $(GOOGLEAPIS_PROTOS_DIR)/google/bigtable/admin/v2/common.proto \
	    $(GOOGLEAPIS_PROTOS_DIR)/google/bigtable/admin/v2/instance.proto \
	    $(GOOGLEAPIS_PROTOS_DIR)/google/bigtable/admin/v2/table.proto \
	# Move the newly generated *_pb2.py files into our library.
	cp $(GENERATED_DIR)/google/bigtable/v2/* $(BIGTABLE_DIR)
	cp $(GENERATED_DIR)/google/bigtable/admin/v2/* $(BIGTABLE_DIR)
	# Remove all existing *.proto files before we replace
	rm -f $(BIGTABLE_DIR)/*.proto
	# Copy over the *.proto files into our library.
	cp $(GOOGLEAPIS_PROTOS_DIR)/google/bigtable/v2/*.proto $(BIGTABLE_DIR)
	cp $(GOOGLEAPIS_PROTOS_DIR)/google/bigtable/admin/v2/*.proto $(BIGTABLE_DIR)
	# Rename all *.proto files in our library with an
	# underscore and remove executable bit.
	cd $(BIGTABLE_DIR) && \
	    for filename in *.proto; do \
	        chmod -x $$filename ; \
	        mv $$filename _$$filename ; \
	    done
	GRPCIO_VIRTUALENV="$(GRPCIO_VIRTUALENV)" \
	# Rewrite the imports in the generated *_pb2.py files.
	python scripts/rewrite_imports.py $(BIGTABLE_DIR)/*pb2.py

clean:
	rm -fr $(GRPCIO_VIRTUALENV) $(GOOGLEAPIS_PROTOS_DIR) $(GENERATED_DIR)

.PHONY: generate clean
