# The full path to the Makefile
MAKEFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
# The path to the directory of the Makefile
MAKEFILE_DIR := $(realpath $(dir $(MAKEFILE_PATH)))

ASSETSROOT = $(MAKEFILE_DIR)/../assets/
ASSETS = $(wildcard $(ASSETSROOT)/icons/*.png)
ASSETSTOCOPY = $(addprefix assets/,$(ASSETS:$(ASSETSROOT)/%=copy/%))

SHELL := bash

PACKAGES := activities assets client dummy-ui game log server

APPS := server client dummy-ui
OBJS := $(foreach app,$(APPS),$(app)/$(app))
WASM := client/client.wasm webtools/webtools.wasm dummy-ui/dummy-ui.wasm

GOFMT ?= gofumpt -l -w .

GO_BUILDTAGS ?=

.PHONY: all release fmt test check $(OBJS) $(WASM)
all: $(OBJS) $(WASM)

release:
	$(MAKE) GO_BUILDTAGS="-tags release" all

.PHONY: client server dummy-ui
client: client/client
server: server/server
dummy-ui: dummy-ui/dummy-ui

VERBOSE ?= @

assets/copy/%: $(ASSETSROOT)/%
	$(VERBOSE)echo Copying asset $(@F)
	$(VERBOSE)if test \( ! \( -d $(@D) \) \); then mkdir -p $(@D);fi
	$(VERBOSE)cp $< $@

$(OBJS): $(ASSETSTOCOPY)
	$(VERBOSE)echo Building $(@F)
	$(VERBOSE)pushd $(@D) >/dev/null && go build $(GO_BUILDTAGS) && popd >/dev/null

$(WASM): $(ASSETSTOCOPY)
	$(VERBOSE)echo Building $(@F) ...
	$(VERBOSE)pushd $(@D) >/dev/null && env GOOS=js GOARCH=wasm go build $(GO_BUILDTAGS) -o $(@F) && popd >/dev/null

fmt:
	$(VERBOSE)set -e; for package in $(PACKAGES) webtools; do \
		pushd $$package >/dev/null && $(GOFMT); popd >/dev/null; \
	done

test:
	$(VERBOSE)STATUS=0; \
	for package in $(PACKAGES); do \
		if pushd "$$package" >/dev/null; then \
			go test; \
			status="$$?"; \
			if [ "$$status" -ne 0 ]; then STATUS="$$status"; fi; \
			popd >/dev/null; \
		fi; \
	done; \
	exit "$$STATUS"

check:
	$(VERBOSE)STATUS=0; \
	for package in $(PACKAGES); do \
		if pushd "$$package" >/dev/null; then \
			golangci-lint run; \
			status="$$?"; \
			if [ "$$status" -ne 0 ]; then STATUS="$$status"; fi; \
			popd >/dev/null; \
		fi; \
	done; \
	exit "$$STATUS"
