COMPOSE:=docker-compose

ifeq ($(shell which $(COMPOSE) > /dev/null; echo $$?),0)
  # prefer system's docker-compose
else ifeq ($(shell which pipenv > /dev/null; echo $$?),0)
  # fallback to pipenv
  COMPOSE:=$(shell pipenv run which $(COMPOSE))
	$(info found compose as $(COMPOSE))
else
  $(error compose not found, please install)
endif

# need root privileges?
PRIVGROUP:=docker
ifneq ($(findstring $(PRIVGROUP),$(shell groups)),$(PRIVGROUP))
	$(info need to run compose as root)
  COMPOSE:=sudo $(COMPOSE)
endif

CANARY:=node_modules/.yarn-integrity

.PHONY: all
all: develop

%/$(CANARY):
	$(eval image:=$(patsubst %/$(CANARY),%,$@))
	$(COMPOSE) build --pull $(image)
	$(COMPOSE) run --rm $(image) yarn install --production=false

DFILES:=$(wildcard */Dockerfile)
IMAGES:=$(patsubst %/Dockerfile,%,$(DFILES))

.PHONY: develop
develop: $(patsubst %,%/$(CANARY),$(IMAGES))
	$(COMPOSE) up

.PHONY: production
production:
	$(COMPOSE) -f docker-compose.yml -f docker-compose.prod.yml build
	$(COMPOSE) -f docker-compose.yml -f docker-compose.prod.yml up -d
