CURRENT_UID := $(shell id -u):$(shell id -g)
PACKAGE_NAME ?= $(shell jq -r '.name' package.json)
PACKAGE_VERSION?= $(shell jq -r '.version' package.json)
BUILD_DATE   ?=$(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
DOCKER_ARGS  ?=
DOCKER_NS    ?= registry.gitlab.com/digiresilience/link/${PACKAGE_NAME}
DOCKER_TAG   ?= test
DOCKER_BUILD := docker build ${DOCKER_ARGS} --build-arg BUILD_DATE=${BUILD_DATE}
DOCKER_BUILD_FRESH := ${DOCKER_BUILD} --pull --no-cache
DOCKER_BUILD_ARGS := --build-arg VCS_REF=${CI_COMMIT_SHORT_SHA}
DOCKER_PUSH  := docker push
DOCKER_BUILD_TAG := ${DOCKER_NS}:${DOCKER_TAG}

.PHONY: .npmrc
.EXPORT_ALL_VARIABLES:

.npmrc:
ifdef CI_JOB_TOKEN
	echo '@guardianproject-ops:registry=https://gitlab.com/api/v4/packages/npm/' > .npmrc
	echo '@digiresilience:registry=https://gitlab.com/api/v4/packages/npm/' >> .npmrc
	echo '//gitlab.com/api/v4/packages/npm/:_authToken=${CI_JOB_TOKEN}' >> .npmrc
	echo '//gitlab.com/api/v4/projects/:_authToken=${CI_JOB_TOKEN}' >> .npmrc
	echo '//gitlab.com/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}' >> .npmrc
endif

docker/build: .npmrc
	DOCKER_BUILDKIT=1 ${DOCKER_BUILD} ${DOCKER_BUILD_ARGS} -t ${DOCKER_BUILD_TAG} ${PWD}

docker/build-fresh: .npmrc
	DOCKER_BUILDKIT=1 ${DOCKER_BUILD_FRESH} ${DOCKER_BUILD_ARGS} -t ${DOCKER_BUILD_TAG} ${PWD}

docker/add-tag:
	docker pull ${DOCKER_NS}:${DOCKER_TAG}
	docker tag ${DOCKER_NS}:${DOCKER_TAG} ${DOCKER_NS}:${DOCKER_TAG_NEW}
	docker push ${DOCKER_NS}:${DOCKER_TAG_NEW}

docker/push:
	${DOCKER_PUSH} ${DOCKER_BUILD_TAG}

docker/build-push: docker/build docker/push
docker/build-fresh-push: docker/build-fresh docker/push

# don't use this to generate passwords for production
generate-secrets:
	ZAMMAD_DATABASE_PASSWORD=$(shell openssl rand -hex 16)
	METAMIGO_DATABASE_ROOT_PASSWORD=$(shell openssl rand -hex 16)
	METAMIGO_DATABASE_PASSWORD=$(shell openssl rand -hex 16)
	METAMIGO_DATABASE_AUTHENTICATOR_PASSWORD=$(shell openssl rand -hex 16)
	NEXTAUTH_AUDIENCE=$(shell openssl rand -hex 16)
	NEXTAUTH_SECRET=$(shell openssl rand -hex 16)

generate-keys:
	docker exec -i $(shell docker ps -aqf "name=metamigo-frontend") bash -c "/opt/metamigo/cli gen-jwks"

setup-signal:
	mkdir -p signald

create-admin-user:
	docker exec -i $(shell docker ps -aqf "name=metamigo-postgresql") bash < ./scripts/create-admin-user.sh


.env:
	@test -f .env || echo "You must create .env please refer to the README" && exit 1

start: .env
	CURRENT_UID=$(CURRENT_UID) docker compose -f docker-compose.link.yml up -d

start-dev: .env
	CURRENT_UID=$(CURRENT_UID) docker compose up --build -d

restart: .env
	CURRENT_UID=$(CURRENT_UID) docker restart $(shell docker ps -a -q)

stop:
	CURRENT_UID=$(CURRENT_UID) docker compose down

destroy:
	docker compose down
	docker volume prune


dev-metamigo:
	CURRENT_UID=$(CURRENT_UID) docker compose  up -d metamigo-postgresql signald
