# Environment section  -----------------------------------------------------

ifneq (,$(wildcard ./.env))
        include .env
        $(eval export $(shell sed -ne 's/ *#.*$$//; /./ s/=.*$$// p' .env))
# Create frontend/.env file
#    $(shell export WS_PORT=$(WS_PORT) ;\
#            export WEB_PORT=$(WEB_PORT) ;\
#            export APP_ADDR=$(APP_ADDR) ;\
#     awk '!/^ *#/ && NF' .env | grep FRONTEND_ | sed 's/FRONTEND_//' | envsubst > frontend/.env)
endif

appName = ${COMPOSE_PROJECT_NAME}
ifeq ($(appName),)
	appName = strprfcrm
endif
args = $(filter-out $@,$(MAKECMDGOALS))

# Docker section -----------------------------------------------------

# uid and group of current user
$(eval export UID=$(shell id -u))
$(eval export GID=$(shell id -g))

ifneq ("$(wildcard docker-compose.local.yml)","")
	compose = docker compose -f docker-compose.yml -f docker-compose.local.yml -p $(appName)
	compose-debug = docker compose -f docker-compose.yml -f docker-compose.local.yml -f docker-compose.debug.yml -p $(appName)
else
	compose = docker compose -f docker-compose.yml -p $(appName)
	compose-debug = docker compose -f docker-compose.yml -f docker-compose.debug.yml -p $(appName)
endif
get_container_name = $(shell docker inspect -f '{{.Name}}' $(shell $(compose) ps -q $(1)) | sed -e 's~^/~~' | tr -d ' ')
message = @echo "\n========================================\n$(1)\n========================================\n"

#
# Containers
#
application = docker exec -it $(call get_container_name, "app")
queue = docker exec -it $(call get_container_name, "app-queue")
websocket = docker exec -it $(call get_container_name, "websocket")
webserver = docker exec -it $(call get_container_name, "webserver")
mysql = docker exec -it $(call get_container_name, "db")

# Commands section -----------------------------------------------------

.DEFAULT_GOAL := help
.PHONY: help

help:
	@grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) \
	| sed -n 's/^\(.*\): \(.*\)##\(.*\)/\1 - \3/p' \
	| column -t -s ' '

install: up-build composer-install db-migrate db-seed frontend-build ## Установка приложения
	$(call message,"The application was successfully installed!")

upgrade: stop pull up-rebuild composer-install db-migrate frontend-build ## Обновление приложения
	$(call message,"The application was successfully updated!")

full-upgrade: stop pull up-rebuild composer-install db-migrate-refresh frontend-build ## Обновление приложения и пересоздание БД
	$(call message,"The application was successfully updated! Database rebuilt!")

up: ## Запуск проекта
	$(compose) up -d

up-debug: ## Запуск проекта в режиме отладки
	$(compose-debug) up -d

remove:
	$(compose) rm -f -s -v

pull:
	$(compose) pull

update:
	pull up

stop:
	$(compose) stop

rm:
	$(compose) rm

up-build:
	$(compose) up --build -d

up-rebuild: ## Перестройка проекта
	$(compose) up --build --force-recreate -d

ps: ## Список запущенных контейнеров
	$(compose) ps

frontend-build: ## Перестроить фронт приложения
	$(webserver) sh -c 'npm install && npm run build'

composer: ## Запуск composer
	$(application) composer $(args)

composer-require: ## Добавление пакета
	$(application) composer require $(args)

composer-install: ## Установка пакетов
	$(application) composer install

composer-regenerate: ## Перестройка пакетов
	$(application) composer dump-autoload

db-migrate: ## Применение миграций
	$(application) php artisan migrate

db-seed: ## Запуск сидеров
	$(application) php artisan db:seed

db-rollback: ## Откат последней миграций
	$(application) php artisan migrate:rollback

db-migrate-refresh: ## Применение миграций с очисткой БД
	$(application) php artisan migrate:fresh --seed

application: ## Консоль приложения
	$(application) bash

pa: ## Консоль приложения
	$(application) php artisan ${args}

route-list: ## Список маршрутов
	$(application) php artisan route:list ${args}

application-log: ## Лог выполнения задач
	$(compose) logs app -f

queue: ## Консоль выполненных задач
	$(queue) bash

qr:	queue-restart

queue-restart: ## Перезапуск очереди
	$(compose) restart app-queue

queue-run: ## Запуск текущих задач
	$(compose) run --rm app-queue php artisan queue:work --once

queue-run-debug:
	$(compose-debug) run --rm app-queue php artisan queue:work --once

queue-log: ## Лог приложения
	$(compose) logs app-queue -f

websocket: ## Консоль приложения websocket
	$(websocket) bash

websocket-log: ## Лог приложения websocket
	$(compose) logs websocket -f

webserver: ## Консоль приложения webserver
	$(webserver) sh

webserver-log: ## Лог приложения webserver
	$(compose) logs webserver -f

mysql: ## Консоль приложения mysql
	$(mysql) bash

log: ## Лог контейнеров
	$(compose) logs -f

# Remove error message about lacking rules for targets' parameters
%:
	@:
