# Minimal build rules for the Zig CLI (no build.zig)

ZIG       ?= zig
BUILD_DIR ?= zig-out/bin
BINARY    := $(BUILD_DIR)/ml

.PHONY: all prod dev test build-rsync build-sqlite install clean help

RSYNC_VERSION ?= 3.3.0
RSYNC_SRC_BASE ?= https://download.samba.org/pub/rsync/src
RSYNC_TARBALL ?= rsync-$(RSYNC_VERSION).tar.gz
RSYNC_TARBALL_SHA256 ?= 7399e9a6708c32d678a72a63219e96f23be0be2336e50fd1348498d07041df90

SQLITE_VERSION ?= 3480000
SQLITE_YEAR ?= 2025
SQLITE_SRC_BASE ?= https://www.sqlite.org/2025

all: $(BINARY)

$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)

$(BINARY): | $(BUILD_DIR)
	$(ZIG) build --release=small

UNAME_S := $(shell uname -s)

ifeq ($(UNAME_S),Linux)
    PROD_DEPS := build-rsync build-sqlite
else
    PROD_DEPS := build-sqlite
endif

# Production build: optimized for speed with ReleaseFast + LTO
prod: $(PROD_DEPS) | $(BUILD_DIR)
	$(ZIG) build --release=fast

# Tiny build: smallest binary with ReleaseSmall
# Note: Requires SQLite amalgamation
.PHONY: tiny
tiny: $(PROD_DEPS) | $(BUILD_DIR)
	$(ZIG) build --release=small

# Development build: fast compilation + optimizations
dev: src/main.zig | $(BUILD_DIR)
	$(ZIG) build --release=fast

# Debug build: fastest compilation, no optimizations
.PHONY: debug
debug: src/main.zig | $(BUILD_DIR)
	$(ZIG) build -Doptimize=Debug

test:
	$(ZIG) build test

build-rsync:
	@RSYNC_VERSION="$(RSYNC_VERSION)" \
	RSYNC_SRC_BASE="$(RSYNC_SRC_BASE)" \
	RSYNC_TARBALL="$(RSYNC_TARBALL)" \
	RSYNC_TARBALL_SHA256="$(RSYNC_TARBALL_SHA256)" \
	bash "$(CURDIR)/scripts/build_rsync.sh"

build-sqlite:
	@SQLITE_VERSION="${SQLITE_VERSION:-3480000}" \
	SQLITE_YEAR="${SQLITE_YEAR:-2025}" \
	SQLITE_SRC_BASE="$(SQLITE_SRC_BASE)" \
	bash "$(CURDIR)/scripts/build_sqlite.sh"

install: $(BINARY)
	install -d $(DESTDIR)/usr/local/bin
	install -m 0755 $(BINARY) $(DESTDIR)/usr/local/bin/ml

clean:
	rm -rf $(BUILD_DIR) zig-out .zig-cache

help:
	@echo "Targets:"
	@echo "  prod    - build production binary with ReleaseFast + LTO (best performance)"
	@echo "  tiny    - build minimal binary with ReleaseSmall (smallest size)"
	@echo "  dev     - build development binary with ReleaseFast (quick builds)"
	@echo "  debug   - build debug binary with no optimizations (fastest compile)"
	@echo "  all     - build release-small binary (legacy, same as 'tiny')"
	@echo "  test    - run Zig unit tests"
	@echo "  build-rsync - build pinned rsync from official source into src/assets"
	@echo "  build-sqlite - fetch SQLite amalgamation into src/assets"
	@echo "  install - copy binary into /usr/local/bin"
	@echo "  clean   - remove build artifacts"