
.PHONY: generate
generate:
	./genproto.sh
	go generate ./...

.PHONY: test
test:
	go test -json ./... | docker run -i ghcr.io/gotesttools/gotestfmt:latest

# ex: make create-migration ARG="create_users_table"
create-migration:
	echo "Creating migration with name $(ARG)"
	docker run -v ./migrations:/migrations --network host migrate/migrate create -ext sql -seq -dir /migrations $(ARG)

# ---- Database access ----

dev-database:
	kubectl run postgres-client \
		--rm -it --image=postgres:latest \
		--env="LLINK_POSTGRES_CONNECTION_URL=$$(kubectl get secret shared-secrets -o jsonpath='{.data.LLINK_POSTGRES_CONNECTION_URL}' --context dev | base64 --decode)" \
		--context dev \
		--command -- /bin/bash -c "psql \$$LLINK_POSTGRES_CONNECTION_URL"

prod-database:
	kubectl run postgres-client \
		--rm -it --image=postgres:latest \
		--env="LLINK_POSTGRES_CONNECTION_URL=$$(kubectl get secret shared-secrets -o jsonpath='{.data.LLINK_POSTGRES_CONNECTION_URL}' --context prod | base64 --decode)" \
		--context prod \
		--command -- /bin/bash -c "psql \$$LLINK_POSTGRES_CONNECTION_URL"

# ---- Migrations ----
# NOTE: if you run into issues with 'dirty' migrations: https://github.com/golang-migrate/migrate/issues/282#issuecomment-530743258

DEV_REPO := us-west2-docker.pkg.dev/flowy-dev-440017/deployments
PROD_REPO := us-west2-docker.pkg.dev/flowy-prod-440017/deployments

.PHONY: migrate-dev
migrate-dev:
	kubectl delete job migrations --ignore-not-found --context=dev
	SKAFFOLD_DEFAULT_REPO=$(DEV_REPO) skaffold run -p migrations --kube-context dev --tail

.PHONY: migrate-prod
migrate-prod:
	kubectl delete job migrations --ignore-not-found --context=prod
	SKAFFOLD_DEFAULT_REPO=$(PROD_REPO) skaffold run -p migrations --kube-context prod --tail

# ---- Deploy ----
# Use MODULE=orion or MODULE=particleprocessor or MODULE=pusher or MODULE=emailnotifierjob to deploy a single service, e.g.:
#   make deploy-dev MODULE=orion

.PHONY: deploy-dev
deploy-dev: generate test
	SKAFFOLD_DEFAULT_REPO=$(DEV_REPO) skaffold run -p dev $(if $(MODULE),-m $(MODULE)) --kube-context dev --port-forward --tail

.PHONY: deploy-prod
deploy-prod: generate test
	SKAFFOLD_DEFAULT_REPO=$(PROD_REPO) skaffold run -p prod $(if $(MODULE),-m $(MODULE)) --kube-context prod --port-forward --tail
