# mitmux build automation. Plain `make` builds both binaries for the
# current platform into bin/; `make release` cross-compiles every
# binary for every platform in PLATFORMS into dist/. Every target here
# is CGO_ENABLED=0 - modernc.org/sqlite is pure Go, so no C toolchain
# is needed on any platform, cross-compiling included.

BIN_DIR  := bin
DIST_DIR := dist

VERSION := $(shell git describe --tags --dirty --always 2>/dev/null || echo dev)
COMMIT  := $(shell git rev-parse --short HEAD 2>/dev/null || echo unknown)
DATE    := $(shell date -u +%Y-%m-%d)
LDFLAGS := -X mitmux/internal/version.Version=$(VERSION) -X mitmux/internal/version.Commit=$(COMMIT) -X mitmux/internal/version.Date=$(DATE)

# darwin/amd64 and freebsd/amd64 cross-compile and pass `go vet` cleanly
# (verified) but, unlike linux/amd64, have not been run on real hardware
# - see README's Platforms section.
PLATFORMS := linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64 freebsd/amd64

.PHONY: all build test check clean release install

all: build

build:
	mkdir -p $(BIN_DIR)
	CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o $(BIN_DIR)/mitmuxd ./cmd/mitmuxd
	CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o $(BIN_DIR)/mitmux  ./cmd/mitmux

# Same checks expected before every commit in this repo - see PLAN.md.
test:
	go build ./...
	go vet ./...
	test -z "$$(gofmt -l .)"
	go test ./...

check: test

clean:
	rm -rf $(BIN_DIR) $(DIST_DIR)

install:
	go install -ldflags "$(LDFLAGS)" ./cmd/mitmuxd
	go install -ldflags "$(LDFLAGS)" ./cmd/mitmux

# Cross-compiles both binaries for every platform in PLATFORMS into
# dist/mitmux-<os>-<arch>/.
release:
	@for p in $(PLATFORMS); do \
		os=$$(echo $$p | cut -d/ -f1); \
		arch=$$(echo $$p | cut -d/ -f2); \
		out=$(DIST_DIR)/mitmux-$$os-$$arch; \
		ext=""; \
		if [ "$$os" = "windows" ]; then ext=".exe"; fi; \
		mkdir -p $$out; \
		echo "building $$os/$$arch..."; \
		CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -ldflags "$(LDFLAGS)" -o $$out/mitmuxd$$ext ./cmd/mitmuxd || exit 1; \
		CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -ldflags "$(LDFLAGS)" -o $$out/mitmux$$ext  ./cmd/mitmux  || exit 1; \
	done
	@echo "release binaries in $(DIST_DIR)/"
