#  hate-no-d
#
#  Native platforms are auto-detected from uname. Cross targets are explicit:
#      make
#      make PLATFORM=Android ANDROID_NDK=/opt/android-ndk [ANDROID_ABI=... ANDROID_API=...]
#      make PLATFORM=Windows WIN_ARCH=x86_64        (cross build with mingw-w64)
#
#  Targets:
#      make            the CLI (hate-no-d or hate-no-d.exe)
#      make help       every target and option
#
#  raylib is linked into the CLI. Objects, rlparser and its generated API tables
#  go to build/; only the CLI and hate-no-d.lua land in the repository root.
#  raylib and LuaJIT build in their own trees (both gitignore their output).

# luajit requires GNU Make. BSD make fails on .FEATURES before this guard.
ifndef .FEATURES
	$(error This build requires GNU Make -- on BSD use 'gmake')
endif

.DEFAULT_GOAL := all

LUAJIT_DIR  := submodules/luajit
LUAJIT_SRC  := $(LUAJIT_DIR)/src
LUAJIT_AR   := $(LUAJIT_SRC)/libluajit.a
RAYLIB_DIR  := submodules/raylib
RAYLIB_SRC  := $(RAYLIB_DIR)/src
RAYLIB_AR   := $(RAYLIB_SRC)/libraylib.a
RLPARSER_DIR := $(RAYLIB_DIR)/tools/rlparser
BUILD_DIR   := build
API_DIR     := $(BUILD_DIR)/api
RLPARSER    := $(BUILD_DIR)/rlparser
RAYLIB_API  := $(API_DIR)/raylib_api.lua
BINDING     := hate-no-d.lua
OBJ         := $(BUILD_DIR)/hate-no-d.o
BIN         := hate-no-d

GEN_FLAGS := --raylib=$(API_DIR)/raylib_api.lua \
             --rlgl=$(API_DIR)/rlgl_api.lua \
             --raymath=$(API_DIR)/raymath_api.lua

# Archiver passed to raylib's build. Cross toolchains ship their own.
AR ?= ar

LUAJIT_XCFLAGS := -DLUAJIT_ENABLE_LUA52COMPAT
LUAJIT_EXTRA   :=

# Platform detection. PLATFORM= always wins over uname.
PLATFORM ?= $(shell uname -s)

ifeq ($(PLATFORM),Linux)
  OS_KIND := linux
else ifeq ($(PLATFORM),Android)
  OS_KIND := android
else ifeq ($(PLATFORM),Darwin)
  OS_KIND := macos
else ifeq ($(PLATFORM),Windows)
  OS_KIND := windows
else ifneq (,$(filter MINGW% MSYS% CYGWIN%,$(PLATFORM)))
  # Native MinGW/MSYS2/Cygwin shell: uname reports e.g. MINGW64_NT-10.0.
  OS_KIND := windows
  PLATFORM := Windows
  MINGW_ARCH := $(shell uname -m)
  ifeq ($(MINGW_ARCH),amd64)
    WIN_ARCH ?= x86_64
  else ifeq ($(MINGW_ARCH),x86)
    WIN_ARCH ?= i686
  else
    WIN_ARCH ?= $(MINGW_ARCH)
  endif
else ifneq (,$(filter $(PLATFORM),FreeBSD OpenBSD NetBSD DragonFly))
  OS_KIND := bsd
endif

# raylib build args; per-platform overrides follow.
RAYLIB_MAKE_ARGS := PLATFORM=PLATFORM_DESKTOP RAYLIB_LIBTYPE=STATIC
RAYLIB_LINK      := -Wl,--whole-archive $(RAYLIB_AR) -Wl,--no-whole-archive

# Linux (ELF)
ifeq ($(OS_KIND),linux)
  EXPORT_LDFLAGS := -Wl,-E
  PLAT_LIBS      := -lm -ldl -lGL -lX11 -lpthread -lrt
  LINK_TARGET    := $(BIN)
endif

# BSD (ELF, dlopen lives in libc)
ifeq ($(OS_KIND),bsd)
  EXPORT_LDFLAGS := -Wl,-E
  # ld searches /usr/lib only. pkg(8) installs into /usr/local (FreeBSD,
  # DragonFly), pkgsrc into /usr/pkg (NetBSD), and base X11 lives in
  # /usr/X11R6 (OpenBSD) or /usr/X11R7 (NetBSD), so every -l below needs an
  # explicit -L. raylib's own BSD link list omits the X11 set and these paths,
  # which is why its examples only link on a system with the libs on the
  # default search path.
  BSD_LIBDIRS    := -L/usr/local/lib
  ifneq (,$(filter OpenBSD NetBSD,$(PLATFORM)))
    BSD_LIBDIRS  += -L/usr/pkg/lib -L/usr/X11R6/lib -L/usr/X11R7/lib
  endif
  PLAT_LIBS      := $(BSD_LIBDIRS) -lm -lGL -lpthread \
                    -lX11 -lXrandr -lXinerama -lXi -lXcursor
  ifneq (,$(filter $(PLATFORM),OpenBSD NetBSD))
    PLAT_LIBS    += -lossaudio
  endif
  LINK_TARGET    := $(BIN)
endif

# Windows (PE, cross-compiled from a POSIX host with mingw-w64; native builds use
# build.bat). i686 needs a 32-bit host compiler, since LuaJIT's buildvm runs
# natively and must match the target pointer size:
#   make PLATFORM=Windows WIN_ARCH=i686 HOST_CC="gcc -m32"
ifeq ($(OS_KIND),windows)
  WIN_ARCH ?= x86_64

  ifeq ($(filter $(WIN_ARCH),x86_64 i686),)
    $(error WIN_ARCH must be x86_64 or i686)
  endif

  CC          := $(WIN_ARCH)-w64-mingw32-gcc
  AR          := $(WIN_ARCH)-w64-mingw32-ar
  HOST_CC     ?= gcc
  PLAT_LIBS   := -lm -lopengl32 -lgdi32 -lwinmm
  BIN         := $(BIN).exe
  LINK_TARGET := $(BIN)

  # raylib detects the host's OS, so pin the target for cross builds.
  RAYLIB_MAKE_ARGS := PLATFORM=PLATFORM_DESKTOP RAYLIB_LIBTYPE=STATIC PLATFORM_OS=WINDOWS

  # Export the exe's symbols so ffi.C can resolve raylib on Windows.
  EXPORT_LDFLAGS := -Wl,--export-all-symbols

  # LuaJIT derives HOST_CC from CC: label both, or the host tools are built with
  # the cross compiler.
  LUAJIT_EXTRA := "CC=$(CC)" "HOST_CC=$(HOST_CC)" TARGET_SYS=Windows
endif

# macOS (Mach-O). ld64 exports main-executable globals by default;
# -export_dynamic keeps -dead_strip/LTO from discarding the Lua API. JIT under
# the hardened runtime needs MAP_JIT, so the deployment target must be >= 11.0.
ifeq ($(OS_KIND),macos)
  ifeq ($(origin CC),default)
    CC := clang
  endif
  MACOSX_DEPLOYMENT_TARGET ?= 11.0
  export MACOSX_DEPLOYMENT_TARGET

  EXPORT_LDFLAGS := -Wl,-export_dynamic
  PLAT_LIBS      := -lm -framework OpenGL -framework Cocoa -framework IOKit \
                    -framework CoreAudio -framework CoreVideo -framework QuartzCore
  LINK_TARGET    := $(BIN)

  # ld64 has no --whole-archive.
  RAYLIB_LINK := -Wl,-force_load,$(RAYLIB_AR)

  # MAP_JIT path, needed for the hardened runtime (and thus notarization).
  MACOSX_HRT ?= 1
  ifeq ($(MACOSX_HRT),1)
    LUAJIT_XCFLAGS += -DLUAJIT_ENABLE_OSX_HRT
  endif
endif

# Android (ELF, cross-compiled with the NDK)
#
# 64-bit ABIs build on any 64-bit host. armeabi-v7a additionally needs a
# 32-bit host compiler:  make ... HOST_CC="gcc -m32"
ifeq ($(OS_KIND),android)
  ANDROID_NDK ?= $(ANDROID_NDK_HOME)
  ANDROID_API ?= 21
  ANDROID_ABI ?= arm64-v8a

  ifeq ($(strip $(ANDROID_NDK)),)
    $(error PLATFORM=Android requires ANDROID_NDK (or ANDROID_NDK_HOME) to be set)
  endif

  ifneq (,$(filter MINGW% MSYS% CYGWIN%,$(shell uname -s)))
    $(error PLATFORM=Android must be built from a Linux or macOS host)
  endif

  ifeq ($(ANDROID_ABI),arm64-v8a)
    ANDROID_TRIPLET := aarch64-linux-android
  else ifeq ($(ANDROID_ABI),armeabi-v7a)
    ANDROID_TRIPLET := armv7a-linux-androideabi
  else ifeq ($(ANDROID_ABI),x86_64)
    ANDROID_TRIPLET := x86_64-linux-android
  else ifeq ($(ANDROID_ABI),x86)
    ANDROID_TRIPLET := i686-linux-android
  else
    $(error ANDROID_ABI must be one of: arm64-v8a, armeabi-v7a, x86_64, x86)
  endif

  ifeq ($(shell uname -s),Darwin)
    ANDROID_HOST_TAG ?= darwin-x86_64
  else
    ANDROID_HOST_TAG ?= linux-x86_64
  endif

  ANDROID_BIN := $(ANDROID_NDK)/toolchains/llvm/prebuilt/$(ANDROID_HOST_TAG)/bin
  ANDROID_CC  := $(ANDROID_BIN)/$(ANDROID_TRIPLET)$(ANDROID_API)-clang

  ifeq ($(ANDROID_ABI),arm64-v8a)
    RAYLIB_ANDROID_ARCH := arm64
  else ifeq ($(ANDROID_ABI),armeabi-v7a)
    RAYLIB_ANDROID_ARCH := arm
  else ifeq ($(ANDROID_ABI),x86_64)
    RAYLIB_ANDROID_ARCH := x86_64
  else
    RAYLIB_ANDROID_ARCH := x86
  endif
  RAYLIB_MAKE_ARGS := PLATFORM=PLATFORM_ANDROID RAYLIB_LIBTYPE=STATIC \
      ANDROID_NDK=$(ANDROID_NDK) ANDROID_ARCH=$(RAYLIB_ANDROID_ARCH) \
      ANDROID_API_VERSION=$(ANDROID_API)

  CC             := $(ANDROID_CC)
  AR             := $(ANDROID_BIN)/llvm-ar
  EXPORT_LDFLAGS := -Wl,-E
  # -Wl,--wrap=fopen is raylib's APK asset hook.
  PLAT_LIBS      := -lm -llog -landroid -lEGL -lGLESv2 -lOpenSLES -ldl -Wl,--wrap=fopen
  LINK_TARGET    := $(BIN)

  LUAJIT_EXTRA := CROSS=$(ANDROID_BIN)/$(ANDROID_TRIPLET)- \
      STATIC_CC=$(ANDROID_CC) TARGET_LD=$(ANDROID_CC) \
      "TARGET_AR=$(ANDROID_BIN)/llvm-ar rcus" \
      TARGET_STRIP=$(ANDROID_BIN)/llvm-strip TARGET_SYS=Linux
endif

ifndef LINK_TARGET
$(error Unsupported platform '$(PLATFORM)' -- supported: Linux, Android, Darwin, Windows, BSD)
endif

# Host compiler for build-time tools (rlparser); the Windows branch pins gcc.
HOST_CC ?= cc
LUAJIT  ?= luajit

# raylib's RELEASE build appends -O1; -O2 is a big win for CPU-bound code.
# Changing it needs `make clean` -- objects are not flag-aware.
RAYLIB_OPT ?= -O2
RAYLIB_MAKE_ARGS += CUSTOM_CFLAGS="$(RAYLIB_OPT)"

# Compiler / linker flags
CFLAGS   ?= -O2 -Wall
CPPFLAGS += -I$(LUAJIT_SRC)

# LuaJIT: static archive only, built through the upstream GNU Makefile.
LUAJIT_MAKE_ARGS := BUILDMODE=static XCFLAGS="$(LUAJIT_XCFLAGS)" $(LUAJIT_EXTRA)

$(LUAJIT_AR):
	$(MAKE) -C $(LUAJIT_SRC) $(LUAJIT_MAKE_ARGS) "LJCORE_O=ljamalg.o" libluajit.a

# raylib: static archive only; CC/AR are pinned, its Makefile defaults to host gcc/ar.
$(RAYLIB_AR):
	$(MAKE) -C $(RAYLIB_SRC) $(RAYLIB_MAKE_ARGS) CC="$(CC)" AR="$(AR)"

# Targets
help:
	@echo "hate-no-d -- LuaJIT-based Lua runtime"
	@echo ""
	@echo "Targets:"
	@echo "  make [all]          CLI for the current platform + hate-no-d.lua"
	@echo "  make bindings       regenerate hate-no-d.lua only"
	@echo "  make check-bindings verify hate-no-d.lua is reproducible and loads"
	@echo "  make print-config   resolved configuration for the current target"
	@echo "  make clean          remove build/ and submodule build artifacts"
	@echo "  make help           this text"
	@echo ""
	@echo "Options (pass as VAR=value):"
	@echo "  PLATFORM=           Linux | Android | Darwin | Windows | a BSD"
	@echo "                      (default: uname -s)"
	@echo "  WIN_ARCH=           x86_64 | i686                          [Windows]"
	@echo "  ANDROID_NDK=        NDK root, or export ANDROID_NDK_HOME   [Android]"
	@echo "  ANDROID_ABI=        arm64-v8a | armeabi-v7a | x86_64 | x86 [Android]"
	@echo "  ANDROID_API=        target API level, default 21           [Android]"
	@echo "  MACOSX_HRT=         hardened-runtime JIT, default 1        [macOS]"
	@echo "  MACOSX_DEPLOYMENT_TARGET=   default 11.0                   [macOS]"
	@echo "  HOST_CC=            host compiler for minilua/buildvm; needed"
	@echo "                      when the target is 32-bit and the host is not"
	@echo "  LUAJIT=             host LuaJIT for the generator, default luajit"
	@echo "  CFLAGS=             default -O2 -Wall"
	@echo "  RAYLIB_OPT=         raylib optimization flags, default -O2"
	@echo "  LDFLAGS=            extra linker flags"
	@echo "  AR=                 archiver for raylib's build"

all: $(LINK_TARGET) $(BINDING)

$(BUILD_DIR):
	@mkdir -p $@

$(API_DIR): | $(BUILD_DIR)
	@mkdir -p $@

$(OBJ): hate-no-d.c | $(BUILD_DIR)
	$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ hate-no-d.c

# raylib is pulled in whole: nothing references it, so the linker would drop it
# and ffi.C would have nothing to resolve.
$(BIN): $(OBJ) $(LUAJIT_AR) $(RAYLIB_AR)
	$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $(OBJ) \
	    $(RAYLIB_LINK) $(LUAJIT_AR) $(EXPORT_LDFLAGS) $(LDFLAGS) $(PLAT_LIBS)

# ---------------------------------------------------------------------------
# Lua bindings (hate-no-d.lua)
#
# gen-hate-no-d.lua turns the rlparser tables for raylib.h, rlgl.h and raymath.h
# into one ffi.cdef block plus constants, wrappers and LuaCATS comments.
#
# The tables are generated into build/api from the pinned submodule headers, so
# raylib's tools/rlparser/output (where raylib_api.lua is tracked) stays clean.
# rlparser itself is built with HOST_CC, never the target CC: cross builds still
# run it to produce the platform-independent binding.
# ---------------------------------------------------------------------------
$(RLPARSER): $(RLPARSER_DIR)/rlparser.c | $(BUILD_DIR)
	$(HOST_CC) -O2 -Wall -std=c99 -o $@ $(RLPARSER_DIR)/rlparser.c

$(RAYLIB_API): $(RLPARSER) $(RAYLIB_SRC)/raylib.h | $(API_DIR)
	$(RLPARSER) -i $(RAYLIB_SRC)/raylib.h -o $@ -f LUA -d RLAPI

$(API_DIR)/rlgl_api.lua: $(RLPARSER) $(RAYLIB_SRC)/rlgl.h | $(API_DIR)
	$(RLPARSER) -i $(RAYLIB_SRC)/rlgl.h -o $@ -f LUA -d RLAPI -t "RLGL IMPLEMENTATION"

$(API_DIR)/raymath_api.lua: $(RLPARSER) $(RAYLIB_SRC)/raymath.h | $(API_DIR)
	$(RLPARSER) -i $(RAYLIB_SRC)/raymath.h -o $@ -f LUA -d RMAPI

$(BINDING): gen-hate-no-d.lua $(API_DIR)/rlgl_api.lua $(API_DIR)/raymath_api.lua $(RAYLIB_API)
	@command -v $(LUAJIT) >/dev/null 2>&1 || { \
	  echo "hate-no-d: cannot run '$(LUAJIT)' -- install LuaJIT or set LUAJIT=..." >&2; exit 1; }
	$(LUAJIT) gen-hate-no-d.lua --out=$@ $(GEN_FLAGS)

bindings: $(BINDING)

# Fail if regeneration is not byte-identical or the module does not load.
check-bindings: $(BINDING)
	$(LUAJIT) gen-hate-no-d.lua --out=$(BUILD_DIR)/hate-no-d.lua.tmp $(GEN_FLAGS)
	cmp $(BINDING) $(BUILD_DIR)/hate-no-d.lua.tmp
	rm -f $(BUILD_DIR)/hate-no-d.lua.tmp
	$(LUAJIT) -e 'local M = dofile("$(BINDING)"); assert(type(M) == "table"); assert(type(M.GetMousePosition) == "function", "raylib"); assert(type(M.rlLoadIdentity) == "function", "rlgl"); assert(type(M.Vector2Add) == "function", "raymath"); print("bindings ok")'

# Resolved configuration for the current target; useful before a cross build.
print-config:
	@echo "PLATFORM                 = $(PLATFORM)"
	@echo "OS_KIND                  = $(OS_KIND)"
	@echo "CC / AR                  = $(CC) / $(AR)"
	@echo "CFLAGS                   = $(CFLAGS)"
	@echo "RAYLIB_OPT               = $(RAYLIB_OPT)"
	@echo "CPPFLAGS                 = $(CPPFLAGS)"
	@echo "EXPORT_LDFLAGS           = $(EXPORT_LDFLAGS)"
	@echo "PLAT_LIBS                = $(PLAT_LIBS)"
	@echo "BSD_LIBDIRS              = $(BSD_LIBDIRS)"
	@echo "LINK_TARGET              = $(LINK_TARGET)"
	@echo "OBJ                      = $(OBJ)"
	@echo "HOST_CC                  = $(HOST_CC)"
	@echo "LUAJIT                   = $(LUAJIT)"
	@echo "BUILD_DIR                = $(BUILD_DIR)"
	@echo "API_DIR                  = $(API_DIR)"
	@echo "RLPARSER                 = $(RLPARSER)"
	@echo "BINDING                  = $(BINDING)"
	@echo "LUAJIT_MAKE_ARGS         = $(LUAJIT_MAKE_ARGS)"
	@echo "RAYLIB_AR                = $(RAYLIB_AR)"
	@echo "RAYLIB_MAKE_ARGS         = $(RAYLIB_MAKE_ARGS)"
	@echo "MACOSX_DEPLOYMENT_TARGET = $(MACOSX_DEPLOYMENT_TARGET) (HRT=$(MACOSX_HRT))"
	@echo "ANDROID_ABI / API        = $(ANDROID_ABI) / $(ANDROID_API)"
	@echo "WIN_ARCH                 = $(WIN_ARCH) (HOST_CC=$(HOST_CC))"

clean:
	@if [ -f $(LUAJIT_DIR)/Makefile ]; then $(MAKE) -C $(LUAJIT_DIR) clean; fi
	@if [ -f $(RAYLIB_SRC)/Makefile ]; then $(MAKE) -C $(RAYLIB_SRC) clean; fi
	rm -rf $(BUILD_DIR)
	rm -f $(BIN) hate-no-d.exe libhate-no-d.a libhate-no-d.a.mri $(LUAJIT_AR) $(RAYLIB_AR)
	rm -f $(BINDING)
	rm -f hate-no-d.o	# object from builds that predate the move into build/

.PHONY: all clean print-config help bindings check-bindings
