# Main Makefile - Platform detection and delegation
# This file is invoked by codermake CLI tool

# Detect platform
OS := $(shell uname -s)

# Include base configuration
include $(CODERMAKE_PACKAGE_DIR)/makefiles/base.mk

# Include platform-specific rules
ifeq ($(OS),OS400)
    # IBM i platform
    include $(CODERMAKE_PACKAGE_DIR)/makefiles/ibmi.mk
else
    # Unix-like platforms (Linux, macOS, FreeBSD, etc.)
    include $(CODERMAKE_PACKAGE_DIR)/makefiles/unix.mk
endif

# Initialize log directory (shared across platforms)
$(shell rm -rf tmp/logs && $(MKDIR) -p tmp/logs)

# Include preprocessed rules from system temp directory
# CODERMAKE_RULES_DIR is set by the codermake CLI to point to /tmp/codermake-<uuid>/
-include $(CODERMAKE_RULES_DIR)/rules.mk
-include $(CODERMAKE_RULES_DIR)/targets.mk

# Detect short-flag invocations like `make -n` or `make -t`. MAKEFLAGS lists
# short flags as the FIRST word with no leading `-` (e.g. "tn"); long options
# follow with their full `--name` form. We only want to match the short chunk
# here — looking at MAKEFLAGS as a whole gives false positives because
# `--output-sync=target` and `--no-builtin-rules` (added by base.mk) contain
# 't' and 'n' as substrings.
MAKE_SHORTFLAGS := $(filter-out -%,$(firstword $(MAKEFLAGS)))

# Per-library bin dirs computed from TARGETS (Unix-like only).
# Under `make -t` / `make -n` recipes don't run, so we pre-create these dirs at
# parse time so dummies inside `build/<lib>.lib/` can be touched. In normal
# builds, the directory rule in unix.mk creates each one on demand.
ifneq ($(OS),OS400)
LIBRARY_BIN_DIRS := $(patsubst %/,%,$(sort $(dir $(filter build/%,$(TARGETS)))))
ifneq (,$(strip $(LIBRARY_BIN_DIRS)))
ifneq (,$(findstring t,$(MAKE_SHORTFLAGS))$(findstring n,$(MAKE_SHORTFLAGS)))
$(shell mkdir -p $(LIBRARY_BIN_DIRS))
endif
endif
endif

# In multi-library output mode, SET_LIBL adds every library in
# CODERMAKE_LIBRARY_LIST to the IBM i library list. Each target's own library
# is already an order-only prereq, but if any target's recipe references
# libraries outside its own (via SET_LIBL), those must also exist first.
# Ensure all libraries used by any target in TARGETS exist before any recipe
# runs by adding them as order-only prereqs to every target.
ifdef CODERMAKE_LIBRARY_MAP
ALL_TARGET_LIB_PATHS := $(patsubst %/,%,$(sort $(dir $(TARGETS))))
ifneq (,$(strip $(ALL_TARGET_LIB_PATHS)))
$(TARGETS): | $(ALL_TARGET_LIB_PATHS)
endif
endif

# Default target
.DEFAULT_GOAL := all
.PHONY: all
all: $(TARGETS)

# Clean target
.PHONY: clean
clean: platform-clean
	@rm -rf tmp/logs
