PORT ?= 5000
IMAGE ?= mimic:latest
CONTAINER ?= mimic
VOLUME ?= mimic-data

.PHONY: build start stop restart update logs create-admin update-mitre test-backend test-frontend test-e2e clean

build:
	docker build -f docker/Dockerfile -t $(IMAGE) .

start:
	docker run -d --name $(CONTAINER) -p $(PORT):5000 -v $(VOLUME):/data --env-file .env $(IMAGE)

stop:
	docker stop $(CONTAINER) && docker rm $(CONTAINER)

restart:
	$(MAKE) stop && $(MAKE) start

update:
	git pull && $(MAKE) build && $(MAKE) restart

logs:
	docker logs -f $(CONTAINER)

create-admin:
ifndef USER
	$(error USER is required: make create-admin USER=alice PASS=p4ssw0rd)
endif
ifndef PASS
	$(error PASS is required: make create-admin USER=alice PASS=p4ssw0rd)
endif
	docker exec $(CONTAINER) flask create-admin $(USER) $(PASS)

MITRE_URL ?= https://raw.githubusercontent.com/mitre/cti/master/enterprise-attack/enterprise-attack.json

update-mitre:
	@mkdir -p backend/data/mitre
	@curl -fsSL "$(MITRE_URL)" -o backend/data/mitre/enterprise-attack.json
	@echo "MITRE bundle updated"
	@if docker ps --format '{{.Names}}' | grep -q "^$(CONTAINER)$$"; then \
		echo "Restarting $(CONTAINER) to reload MITRE bundle..."; \
		docker restart $(CONTAINER); \
	fi

test-backend:
	docker exec $(CONTAINER) pytest -q backend/tests/

test-frontend:
	cd frontend && npm run test -- --run

test-e2e:
	cd e2e && npx playwright test

clean:
	-docker rm -f $(CONTAINER) 2>/dev/null
	-docker volume rm $(VOLUME) 2>/dev/null
	rm -rf backend/__pycache__ frontend/node_modules frontend/dist
