BINARIES=ecload ecload-tui

VERSION=0.1.0
BUILD:=`git rev-parse HEAD`

PLATFORMS=linux darwin windows
ARCHITECTURES=amd64

LDFLAGS=-ldflags "-s -X main.Version=${VERSION} -X main.Build=${BUILD}"

define BUILDER
bin/%/$(TARGET): cmd/$(TARGET)/*.go pkg/ecload/*.go
	GOOS=$$(patsubst %/,%,$$(dir $$*)) GOARCH=$$(notdir $$*) go build $(LDFLAGS) -v -o $$@ cmd/$(TARGET)/main.go
endef

$(foreach TARGET,$(BINARIES),$(eval $(BUILDER)))

dist/%.tar.gz:
	@mkdir -p ./dist

	$(eval TMP := $(shell mktemp -d))

	$(eval SANE=$(subst -,/,$*))
	$(eval INPUT=bin/$(SANE)/)
	$(eval PLATFORM=$(patsubst %/,%,$(dir $(SANE))))

	@cp -r $(INPUT)* $(TMP)

	@if [ "$(PLATFORM)" == "windows" ]; then \
		for FILE in $(TMP)/*; do mv $$FILE $$FILE.exe; done \
	fi

	tar -zcf $@ -C $(TMP) .

	@rm -rf $(TMP)

dist: binaries $(foreach GOOS, $(PLATFORMS), $(foreach GOARCH, $(ARCHITECTURES), dist/$(GOOS)-$(GOARCH).tar.gz))
binaries: $(foreach GOOS, $(PLATFORMS), $(foreach GOARCH, $(ARCHITECTURES), $(foreach BINARY, $(BINARIES), bin/$(GOOS)/$(GOARCH)/$(BINARY))))

all: dist

clean:
	rm -rf bin/ dist/
	go clean ./cmd/ecload ./cmd/ecload-tui ./pkg/ecload

.PHONY: all clean binaries dist
