APP_NAME := netctl
SRC := .
OUTPUT := ./bin/$(APP_NAME).exe
GO := go

# Version info
VERSION := $(shell git describe --tags --abbrev=0)
GIT_COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
BUILD_TIME := $(shell date -u +%Y-%m-%dT%H:%M:%SZ)

# ----------------------------------------------------
# Detect tools (cross‑platform compatible)
# ----------------------------------------------------

# Detect Zig
ifeq ($(OS),Windows_NT)
    ZIG_BIN := $(shell where zig 2>/dev/null)
else
    ZIG_BIN := $(shell which zig 2>/dev/null)
endif

# Detect UPX
ifeq ($(OS),Windows_NT)
    UPX_BIN := $(shell where upx 2>nul)
else
    UPX_BIN := $(shell which upx 2>/dev/null)
endif

# ----------------------------------------------------
# User Options
# ----------------------------------------------------
BRUTE ?= 0        # UPX ultra-brute disabled by default

.PHONY: all build run clean

all: build

# ----------------------------------------------------
# Build
# ----------------------------------------------------
build:
	@mkdir -p ./bin

	@echo "Version: $(VERSION)"
	@echo "Commit:  $(GIT_COMMIT)"
	@echo "Time:    $(BUILD_TIME)"

	# ---------- Zig External Linker ----------
	@if [ -n "$(ZIG_BIN)" ]; then \
		echo "Zig found -> Using Zig as external Go linker"; \
		CGO_ENABLED=0 CC="zig cc" CXX="zig c++" \
		$(GO) build -trimpath -ldflags "-s -w \
			-X netcli/cmd.Version=$(VERSION) \
			-X netcli/cmd.Commit=$(GIT_COMMIT) \
			-X netcli/cmd.BuildTime=$(BUILD_TIME)" \
			-o $(OUTPUT) $(SRC); \
	else \
		echo "Zig not used -> Using Go native linker"; \
		$(GO) build -trimpath -ldflags "-s -w \
			-X netcli/cmd.Version=$(VERSION) \
			-X netcli/cmd.Commit=$(GIT_COMMIT) \
			-X netcli/cmd.BuildTime=$(BUILD_TIME)" \
			-o $(OUTPUT) $(SRC); \
	fi

	# ---------- UPX Compression ----------
	@if [ -n "$(UPX_BIN)" ]; then \
		if [ "$(BRUTE)" = "1" ]; then \
			echo "UPX found -> Using ultra-brute compression..."; \
			upx --ultra-brute $(OUTPUT); \
		else \
			echo "UPX found -> Using normal compression (--best --lzma)..."; \
			upx --best --lzma $(OUTPUT); \
		fi; \
	else \
		echo "UPX not found -> Skipping compression"; \
	fi

# ----------------------------------------------------
# Run without building binary
# ----------------------------------------------------
run:
	$(GO) run -ldflags "-s -w \
		-X netcli/cmd.Version=$(VERSION) \
		-X netcli/cmd.Commit=$(GIT_COMMIT) \
		-X netcli/cmd.BuildTime=$(BUILD_TIME)" $(SRC)

# ----------------------------------------------------
# Clean
# ----------------------------------------------------
clean:
	rm -f $(OUTPUT)
