# Current UID and GID that the containers will be started as
DOCKER_UID = "$(shell id -u):$(shell id -g)"

# Basic docker-compose command
DOCKER_COMPOSE = DOCKER_UID=$(DOCKER_UID) docker-compose

# Commands inside containers
DOCKER_RUN = $(DOCKER_COMPOSE) run --rm app
COMPOSER = $(DOCKER_RUN) composer
PHPUNIT = $(DOCKER_RUN) vendor/bin/phpunit

.PHONY: all clean VERSION \
	docker-up docker-up-detached docker-down docker-restart docker-build docker-rebuild docker-purge docker-logs docker-run \
	composer-install composer-install-no-dev composer-update composer-cmd \
	test phpunit open-coverage

# Default target
all: docker-build composer-install docker-up


# Container management
# --------------------

# Start docker containers in foreground mode, building images if needed
docker-up:
	$(DOCKER_COMPOSE) up --build

# Start docker containers in detached mode
docker-up-detached:
	$(DOCKER_COMPOSE) up --build --detach

# Stop running docker containers
docker-down:
	$(DOCKER_COMPOSE) down

# Restart docker containers (use `make docker-restart SERVICE=foo` to just restart a specific service)
docker-restart:
	$(DOCKER_COMPOSE) restart $(SERVICE)

# Build container images without starting the containers
docker-build:
	$(DOCKER_COMPOSE) build

# Rebuild docker containers from scratch (pulling base images and ignoring cache)
docker-rebuild:
	$(DOCKER_COMPOSE) build --pull --no-cache

# Stop running docker containers and delete all volumes
docker-purge:
	$(DOCKER_COMPOSE) down --volumes

# Show container logs (use `make docker-logs SERVICE=foo` to just select a specific service)
docker-logs:
	$(DOCKER_COMPOSE) logs -f $(SERVICE) || true

# Run command in app container (e.g. `make docker-run CMD="bash"`)
docker-run:
	$(DOCKER_RUN) "$(or $(CMD),bash)"


# Dependency management
# ---------------------

# Install PHP composer dependencies inside the app container
composer-install:
	$(COMPOSER) install

# Install PHP composer dependencies without development dependencies like phpunit
composer-install-no-dev:
	$(COMPOSER) install --no-dev

# Update PHP composer dependencies inside the app container
composer-update:
	$(COMPOSER) update

# Run arbitrary composer commands inside the app container (e.g. `make composer-cmd CMD="help"`)
composer-cmd:
	@test -n "$(CMD)" || (echo "Please use 'make composer-cmd CMD=\"some command\"'"; exit 1)
	$(COMPOSER) $(CMD)


# Test suites
# -----------

# Run all test suites
test: phpunit

# Run phpunit tests
phpunit:
	$(PHPUNIT) -c phpunit.xml --testdox

# Open HTML coverage report in $BROWSER (needs to be generated by phpunit first)
open-coverage:
	$(or $(BROWSER),firefox) coverage/index.html


# Version management
# ------------------

# Create VERSION file from current git tag
version:
	git describe | tee VERSION


# Clean up
# --------

# Remove vendor directory, phpunit caches and other files that have been generated
clean: docker-down
	rm -rf .composer vendor .phpunit.cache coverage VERSION
