# DO NOT EDIT THIS FILE
#
# This file is managed by https://git.wid.la/wid/grand-central
#
# Changes will be overwritten

-include make.env
LANGUAGES := none go react node flutter dart typescript
CODELANGUAGE ?=  $(call GetFromConfig,language)
REPO_NAME ?= $(CI_PROJECT_NAME)
# Deploy
DEPLOY_TOOL ?= $(error DEPLOY_TOOL not set in Env)
DEPLOY_HOST ?= $(error DEPLOY_HOST not set in Env)
DEPLOY_DOMAIN ?= $(error DEPLOY_DOMAIN not set in Env)
DEPLOY_TOKEN ?= $(error DEPLOY_TOKEN not set in Env)
# Build
BUILD_ENGINE ?= "gcloud"
BUILD_REGISTRY ?= $(error BUILD_REGISTRY not set in Env)
BUILD_FORKLIFT ?= "false"
BUILD_CLOUDBUILD ?= "cloudbuild.json"
BUILD_DOCKERFILE ?= "Dockerfile"
# Registry
REGISTRY_NAMESPACE ?= $(error REGISTRY_NAMESPACE not set in Env)
REGISTRY_PUBLIC ?= "false"
# Default Vars
DOCKER_PASS ?= "empty"
DATABASE_NAME ?= "default"
DATABASE_PASSWORD ?= "empty"
DEPLOY_NAME ?= "test"
TAG = $(CI_COMMIT_REF_NAME)
DEPLOY_SERVER = $(DEPLOY_TOOL).$(DEPLOY_HOST).$(DEPLOY_DOMAIN)
GOPKGS = $(go list ./... | grep -v "/vendor/")
GOARCH ?=amd64
upper= $(shell python -c "print('$(1)'[:1].capitalize() + '$(1)'[1:])")
export REPO_NAME
export TAG
export DATABASE_NAME
export BUILD_CLOUDBUILD
export REGISTRY_PUBLIC

#
# COMMANDS
#
define GetFromConfig
$(shell python3 -c "import sys, json; print(json.load(open('./.gc-config.json'))['$(1)'])")
endef

define language_undefined
	@echo "Language is NOT handled" 
endef

define deps_go
	go mod tidy && go mod vendor
endef

define deps_react
	npm install
endef

define deps_flutter
	flutter pub get
endef

define test_go
	# go test -v ./...
endef

define test_react
	@echo "test react"
	node --version
	npm --version
endef

define test_flutter
	@echo "test flutter"
endef

define lint_go
	@echo "Lint Go"
endef
# LINT
# gometalinter --vendor --fast --disable=gotype --disable=gas --disable=errcheck $(GOPKGS)
#

define lint_react
	@echo "Lint react"
	node --version
	npm --version
endef

define setlinter_typescript
	@echo "Setup Linter typescript"
	node --version
	npm --version
	npm install --save-dev prettier
	touch .prettierrc
	npm install --save-dev eslint-config-prettier eslint-plugin-prettier eslint-plugin-jsdoc eslint-plugin-i18next
endef

define lint_typescript
	@echo "Lint typescript"
	node --version
	npm --version
	# npm install eslint-plugin-react@latest --save-dev
	eslint . --ext .ts,.tsx
endef

define lint_flutter
	flutter --version
	flutter analyze
endef

define analyze_react
	sudo node build.js
endef

define install_go
	@go version
	CGO_ENABLED=0 GOGC=off go install -v
endef

define run_go
	$(call install_go)
	set -a && source config/local.env && set +a && $(REPO_NAME)
endef

define run_react
	npm start
endef

define build_none
	@echo "nothing to build"
endef

define version_flutter
	@echo "Version flutter"
	ruby /usr/local/bin/versioning.rb $(1)
    git status
    git config --global user.email "gcbot@wid.la"
    git config --global user.name "GC Bot"
    git checkout -B newVersion_$(2)
    git remote set-url origin https://gc_bot:${GC_ADMIN_TOKEN}@git.wid.la/${CI_PROJECT_PATH}
    git add . && git commit -m 'update version'
    git push --follow-tags origin newVersion_$(2)
	curl --header "Content-Type: application/json" --header "PRIVATE-TOKEN: ${GC_ADMIN_TOKEN}" --request POST --data '{"source_branch":"'newVersion_$(2)'","target_branch":"alpha","title":"AUTO MR: New Version", "remove_source_branch":"yes"}' https://git.wid.la/api/v4/projects/${CI_PROJECT_ID}/merge_requests
endef

define build_go
    if [ ${BUILD_FORKLIFT} = "true" ]; then forklift -extensions SQL,HTML > forklift.go; fi
	if [ ! -d "./fonts" ]; then mkdir ./fonts; fi
	GOOS=linux GOARCH=$(GOARCH) go build -v
endef

define build_react
	sed -i '' "s|_COMMIT_SHA|$(CI_COMMIT_SHA)|g" public/index.html
	sed -i '' "s|_REPO_NAME|$(REPO_NAME)|g" public/version.js
	sed -i '' "s|_COMMIT_REF_NAME|$(CI_COMMIT_REF_NAME)|g" public/version.js
	sed -i '' "s|_COMMIT_SHA|$(CI_COMMIT_SHA)|g" public/version.js
	npm install
    CI=false npm run-script build
	mv public/version.js build/version_$(CI_COMMIT_SHA).js
endef

define gcloud_build
	gcloud builds submit . --config=$(1) \
	 --substitutions _PROJECT_NAMESPACE=$(PROJECT_NAMESPACE),_REPO_NAME=$(REPO_NAME),_TAG=$(CI_COMMIT_REF_NAME),_REGISTRY_NAMESPACE=$(REGISTRY_NAMESPACE),_DOCKER_PASS=$(DOCKER_PASS),_BUILD_DOCKERFILE=$(BUILD_DOCKERFILE),_COMMIT_SHA=$(CI_COMMIT_SHA),_NPM_TOKEN=$(NPM_TOKEN),_COMMIT_REF_NAME=$(CI_COMMIT_REF_NAME),_BUILD_FORKLIFT=$(BUILD_FORKLIFT)
endef

define report_git_repo
	@echo "Report Git Repo id:$(1) $(2)/$(3):$(4) [$(5)]"
	curl --header "Content-Type: application/json" --cookie "auth-server-token=$(TRACKER_BOT_TOKEN)" --request POST  --data '{"name":"$(5)","gitlabID":$(1), "image":"$(2)/$(3)", "latestVersion":"$(4)", "runner":"$(CI_RUNNER_DESCRIPTION)", "buildEngine":"$(BUILD_ENGINE)"}' $(TRACKER_ENDPOINT)/gitRepos
endef

define carebox_deploy
	carebox-client $(1) $(DEPLOY_SERVER)
endef

define db_create
    @echo "db_create $(1)" 
	cp db/db.tmpl db/db.go
	sed -i '' "s|_MODELNAME|$(1)|g" db/db.go
	sed -i '' "s|_CAPMODELNAME|$(upper)|g" db/db.go
	sed -i '' "s|_TABLENAME|$(2)|g" db/db.go
	go run db/db.go create
	rm db/db.go
	dbmigrate new create$(upper)s
endef

define db_update
    @echo "db_create $(1)" 
	cp db/db.tmpl db/db.go
	sed -i '' "s|_MODELNAME|$(1)|g" db/db.go
	sed -i '' "s|_CAPMODELNAME|$(upper)|g" db/db.go
	sed -i '' "s|_TABLENAME|$(2)|g" db/db.go
	go run db/db.go update
	rm db/db.go
	dbmigrate new addFieldsTo$(2)
endef
#
# RULES
#
.PHONY: help language db deps test setlinter lint clean analyze install run start build docker_build gcloud_auth gcloud_build deploy version
help:
	@grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

language: ## Check Language Validity
ifneq ($(filter $(CODELANGUAGE),$(LANGUAGES)),)
	@echo "Language is $(CODELANGUAGE)"
else
	$(language_undefined) 
	@exit 1
endif

db: ## Runs dbmigrate
	$(call db_$(action),$(model),$(table))

deps:  ## Install the project dependencies
	$($@_$(CODELANGUAGE))

test: ## Runs the tests
	$($@_$(CODELANGUAGE))

setlinter: ## Setup the linter
	$($@_$(CODELANGUAGE))

lint: ## Runs the linter
	$($@_$(CODELANGUAGE))

clean: ## Clean repo
	@echo "Clean"

analyze: ## Analyse the bundle
	$($@_$(CODELANGUAGE))

install: ## ## Installs the Go binary
	$($@_$(CODELANGUAGE))

run: ## Run the app
	$($@_$(CODELANGUAGE))

start: ## Launch the app
	$(run_$(CODELANGUAGE))

build: ## Build the app
	$($@_$(CODELANGUAGE))

version: ## Build the app
	$(call $@_$(CODELANGUAGE),$(tag),$(platform))

docker_build: ## Builds the Docker image localy
	@echo "REGISTRY_PUBLIC is $(REGISTRY_PUBLIC)"
ifeq ($(REGISTRY_PUBLIC),true)
	@echo "Public Build"
	docker buildx build --platform linux/amd64 --build-arg REPO_NAME=${REPO_NAME} -t ${REGISTRY_NAMESPACE}/${REPO_NAME}:${CI_COMMIT_REF_NAME} -f ${BUILD_DOCKERFILE} --push .
else
	@echo "Private Build"
	docker buildx build --platform linux/amd64 --build-arg REPO_NAME=${REPO_NAME} -t us.gcr.io/${BUILD_REGISTRY}/${REPO_NAME}:${CI_COMMIT_REF_NAME} -f ${BUILD_DOCKERFILE} --push .
endif

gcloud_auth: ## Authenticates through the gcloud CLI
	@echo $(GCLOUD_SERVICE_KEY) | base64 -d > $(HOME)/gcloud-service-key.json
	gcloud auth activate-service-account --key-file $(HOME)/gcloud-service-key.json
	gcloud config set project $(BUILD_REGISTRY)

gcloud_build: ## Builds the Docker image on gcloud
	@echo "REGISTRY_PUBLIC is $(REGISTRY_PUBLIC)"
ifeq ($(REGISTRY_PUBLIC),true)
	$(call gcloud_build,"cloudbuild_public.json")
else
	$(call gcloud_build,$(BUILD_CLOUDBUILD))
endif

deploy: ## Deploys the Docker image
	@echo "Deploy with $(DEPLOY_NAME) & DEPLOY_SERVER: $(DEPLOY_SERVER)"
	$(call carebox_deploy,$(DEPLOY_NAME))

report_git_repo: ## Report Git Repo Version
ifeq ($(REGISTRY_PUBLIC),true)
	$(call report_git_repo,$(CI_PROJECT_ID),$(REGISTRY_NAMESPACE),$(REPO_NAME),$(CI_COMMIT_REF_NAME),$(CI_PROJECT_TITLE))
else
	$(call report_git_repo,$(CI_PROJECT_ID),$(BUILD_REGISTRY),$(REPO_NAME),$(CI_COMMIT_REF_NAME),$(CI_PROJECT_TITLE))
endif