export CPU_CORES = $(shell cat /proc/cpuinfo | grep '^processor' | wc -l)
export STACK_CORES = $(shell echo $(($(CPU_CORES)/2)))

ifeq ($(PROD),true)
export --DEVELOPMENT=--flag uniworx:-dev
else
export --DEVELOPMENT=--flag uniworx:dev
endif

.PHONY: dependencies
dependencies:
	stack install hpack; stack install yesod-bin; \
	stack build -j2 --only-dependencies

.PHONY: compile
compile: dependencies
	stack build $(STACK_CORES) --fast --profile --library-profiling --executable-profiling --flag uniworx:-library-only $(--DEVELOPMENT) --local-bin-path $$(pwd)/bin --copy-bins

.PHONY: lint
lint:
	stack build $(STACK_CORES) --test --fast --flag uniworx:library-only $(--DEVELOPMENT) uniworx:test:hlint

.PHONY: test
test:
	stack build $(STACK_CORES) --test --coverage --fast --flag uniworx:library-only $(--DEVELOPMENT)

# For Reverse Proxy Problem see: https://groups.google.com/g/yesodweb/c/2EO53kSOuy0/m/Lw6tq2VYat4J
.PHONY: start
start: dependencies
	export YESOD_IP_FROM_HEADER=true; \
	export DEV_PORT_HTTP=3000; \
	export DEV_PORT_HTTPS=3443; \
	export HOST=127.0.0.1 ; \
	export PORT=$${PORT:-$${DEV_PORT_HTTP}} ; \
	export DETAILED_LOGGING=$${DETAILED_LOGGING:-true} ; \
	export LOG_ALL=$${LOG_ALL:-false} ; \
	export LOGLEVEL=$${LOGLEVEL:-info} ; \
	export DUMMY_LOGIN=$${DUMMY_LOGIN:-true} ; \
	export SERVER_SESSION_ACID_FALLBACK=$${SERVER_SESSION_ACID_FALLBACK:-true} ; \
	export SERVER_SESSION_COOKIES_SECURE=$${SERVER_SESSION_COOKIES_SECURE:-false} ; \
	export COOKIES_SECURE=$${COOKIES_SECURE:-false} ; \
	export ALLOW_DEPRECATED=$${ALLOW_DEPRECATED:-true} ; \
	export ENCRYPT_ERRORS=$${ENCRYPT_ERRORS:-false} ; \
	export RIBBON=$${RIBBON:-$${HOST:-localhost}} ; \
	export APPROOT=$${APPROOT:-http://localhost:$${DEV_PORT_HTTP}} ; \
	export AVSPASS=$${AVSPASS:-nopasswordset} ; \
	stack $(STACK_CORES) exec --local-bin-path $$(pwd)/bin --copy-bins -- yesod devel -p "$${DEV_PORT_HTTP}" -q "$${DEV_PORT_HTTPS}"

.PHONY: clean
clean:
	rm -rf .stack-work .stack uniworx.cabal .ghc