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

# Version info
VERSION := 1.0.1
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
DETECTED_ZIG := $(shell command -v zig 2>/dev/null)
DETECTED_UPX := $(shell command -v upx 2>/dev/null)

# User config
ZIG ?= 1          # auto enable zig linker if exists
BRUTE ?= 0        # UPX brute mode disabled by default

.PHONY: all build run clean

all: build

build:
	@mkdir -p ./bin

	@if [ "$(ZIG)" = "1" ] && [ -n "$(DETECTED_ZIG)" ]; then \
		echo "Zig detected -> Using Zig as Go external linker"; \
		export CGO_ENABLED=0; \
		export CC="zig cc"; \
		export 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

	@if [ -n "$(DETECTED_UPX)" ]; then \
		if [ "$(BRUTE)" = "1" ]; then \
			echo "UPX brute mode enabled (--ultra-brute)..."; \
			upx --ultra-brute $(OUTPUT); \
		else \
			echo "UPX detected → Applying normal compression (--best --lzma)..."; \
			upx --best --lzma $(OUTPUT); \
		fi \
	else \
		echo "UPX not found → Skipping compression"; \
	fi

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:
	rm -f $(OUTPUT)
