# Permet d'utiliser un .env.docker.local pour override
ENV_DEFAULT = docker/.env.docker
ENV_LOCAL   = docker/.env.docker.local
ENV_FILE    := $(if $(wildcard $(ENV_LOCAL)),$(ENV_LOCAL),$(ENV_DEFAULT))

# Permet d'avoir les variables du fichier .env.docker.local
include $(ENV_DEFAULT)
-include $(ENV_LOCAL)

PHP_CONTAINER				= php-$(DOCKER_APP_NAME)-fpm
SYMFONY_CONSOLE				= $(EXEC_PHP) php bin/console

DOCKER_COMPOSE = docker compose --env-file $(ENV_FILE)
DOCKER						= docker

EXEC_PHP					= $(DOCKER) exec -t -u $(APP_USER) $(PHP_CONTAINER)
EXEC_PHP_CS_FIXER			= $(EXEC_PHP) php vendor/bin/php-cs-fixer
EXEC_PHP_ROOT				= $(DOCKER) exec -t -u root $(PHP_CONTAINER)
EXEC_PHP_INTERACTIVE		= $(DOCKER) exec -it -u $(APP_USER) $(PHP_CONTAINER)
EXEC_PHP_INTERACTIVE_ROOT	= $(DOCKER) exec -it -u root $(PHP_CONTAINER)
FILES						=

#========================================================================================

env-init:
	@mkdir -p docker
	@cp --update=none $(ENV_DEFAULT) $(ENV_LOCAL)

# Lance le container
start: env-init
	@echo "**** START CONTAINERS ****"
	@cp --update=none docker/.env.docker docker/.env.docker.local
	CURRENT_UID=$(shell id -u) CURRENT_GID=$(shell id -g) $(DOCKER_COMPOSE) up -d

# Éteint le container
stop:
	$(DOCKER_COMPOSE) stop

restart: env-init
	$(DOCKER_COMPOSE) down
	CURRENT_UID=$(shell id -u) CURRENT_GID=$(shell id -g) $(DOCKER_COMPOSE) up -d

install: copy-git-hook composer-install

# Supprime tout est réinstalle tout (Attention ça supprime la bdd aussi)
reset: delete_built_dir remove_orphans build-without-cache start wait install

copy-git-hook:
	$(EXEC_PHP) cp pre-commit .git/hooks/
	$(EXEC_PHP) cp commit-msg .git/hooks/
	$(EXEC_PHP) chmod a+x .git/hooks/pre-commit
	$(EXEC_PHP) chmod a+x .git/hooks/commit-msg

composer-install:
	$(EXEC_PHP) composer install

delete_built_dir:
	CURRENT_UID=$(shell id -u) CURRENT_GID=$(shell id -g) $(DOCKER_COMPOSE) up -d
	$(DOCKER) exec -u root $(PHP_CONTAINER) rm -rf vendor/

remove_orphans:
	$(DOCKER_COMPOSE) kill
	$(DOCKER_COMPOSE) down --volumes --remove-orphans

build-without-cache:
	$(DOCKER_COMPOSE) build	\
		--build-arg="DOCKER_PHP_VERSION=$(DOCKER_PHP_VERSION)" 	\
		--build-arg="DOCKER_NODE_VERSION=$(DOCKER_NODE_VERSION)" 	\
		--build-arg="CURRENT_UID=$(shell id -u)" 	\
		--build-arg="CURRENT_GID=$(shell id -g)" 	\
 		--no-cache

shell:
	$(EXEC_PHP_INTERACTIVE) bash

shell-root:
	$(EXEC_PHP_INTERACTIVE_ROOT) bash

# Lance php fixer
php-cs-fixer-all:
	$(EXEC_PHP) php vendor/bin/php-cs-fixer fix

# Utilisé par le pre-commit pour fix les fichiers modifiés
php-cs-fixer-allow-risky:
	@echo "Fixing files: $(FILES)"
	$(EXEC_PHP_CS_FIXER) fix --config=.php-cs-fixer.dist.php --allow-risky=yes $(FILES)

wait:
	sleep 10

# Lance la suite PHPUnit. Usage : make test                (tout)
#                                  make test FILES=<path>  (un fichier/dossier)
test:
	$(EXEC_PHP) php vendor/bin/phpunit $(FILES)