.PHONY: proto-js .FORCE
SHELL = /bin/bash -o pipefail

PROTODIR=perxis-proto/proto
DSTDIR=clients

ALLPROTO?=$(shell find $(PROTODIR) -name '*.proto' )
PROTOFILES=	$(filter-out proto/status/status.proto, $(ALLPROTO))
PROTOTSFILES=$(ALLPROTO:.proto=.ts)
PROTOJSFILES=$(PROTOFILES:.proto=_pb.js)

PROTOC_MAJOR_VERSION=$(shell protoc --version | awk '{print $$2;}' | cut -d. -f1)
PROTOC_MINOR_VERSION=$(shell protoc --version | awk '{print $$2;}' | cut -d. -f2)
TSC_MAJOR_VERSION=$(shell tsc --version | awk '{print $$2;}' | cut -d. -f1)
TSC_MINOR_VERSION=$(shell tsc --version | awk '{print $$2;}' | cut -d. -f2)
TSC_MIC_VERSION=$(shell tsc --version | awk '{print $$2;}' | cut -d. -f3)

# Генерация js
proto: proto-js

proto-js: protoc-check js-check generate-js $(PROTOTSFILES)
	@echo "Generated all protobuf JavaScrypt files"

%.ts: %.proto
	@protoc -I=$(PROTODIR) \
	--plugin=@protoc-gen-ts_proto \
 	--ts_proto_opt=env=browser,outputServices=generic-definitions,outputJsonMethods=false,esModuleInterop=true,useOptionals=messages,exportCommonSymbols=false,useDate=false,useExactTypes=false \
 	--ts_proto_out=$(DSTDIR) \
 	"$<"

generate-js:
	@./config/generate.sh

proto-clean:
	@rm -f $(PROTOTSFILES) -f $(PROTOJSFILES)

.FORCE:
# Проверка, что установлены необходимые инструменты для генерации proto-файлов
protoc-check:
ifeq (,$(shell which protoc))
	$(error "Protocol Buffers not found. Run for linux: \"sudo apt install -y protobuf-compiler\", for mac: \"brew install protobuf\" \
	or visit \"https://grpc.io/docs/protoc-installation/\" for more.\n")
endif
ifneq ($(shell expr $(PROTOC_MAJOR_VERSION) \>= 3),1)
	 $(error "Current version is outdated. Please update protoc")
endif
ifneq ($(shell expr $(PROTOC_MINOR_VERSION) \>= 21), 1)
	 $(error "Current version is lower than 3.21. Please update protoc")
endif

js-check:
ifeq (,$(shell which npm))
	$(error "NPM not found. Run for linux: \"sudo apt install npm\", for mac: \"brew install npm\" \
	or visit \"https://docs.npmjs.com/getting-started\" for more.\n")
endif
ifeq (,$(shell which protoc-gen-ts_proto))
	$(error "Ts-proto plugin for protoc not found. \
	Run \"npm install -g ts-proto@1.115.5\" \
	or visit \"https://github.com/stephenh/ts-proto\" for more.\n")
endif
ifeq (,$(shell which tsc))
	$(error "Typescript not found. \
	Run \"npm install -g typescript@4.7.4\" \
	or visit \"https://github.com/microsoft/TypeScript\" for more.\n")
endif
ifneq ($(shell expr $(TSC_MAJOR_VERSION) \>= 4), 1)
  	 $(error "Current version is outdated. Please update typescript \n")
endif
ifneq ($(shell expr $(TSC_MINOR_VERSION) \>= 7), 1)
  	 $(error "Current version is lower than 4.7 Please update typescript \n")
endif
ifneq ($(shell expr $(TSC_MIC_VERSION) \>= 4), 1)
  	 $(error "Current version is lower than 4.7.4 Please update typescript \n")
endif