#  hate-no-d
#
#  Native platforms are auto-detected from uname. Cross targets are selected explicitly:
#      make
#      make PLATFORM=Android ANDROID_NDK=/opt/android-ndk
#      make PLATFORM=Android ANDROID_NDK=... ANDROID_ABI=armeabi-v7a ANDROID_API=21
#      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.

# luajit requires GNU Make (use `gmake` on FreeBSD/OpenBSD/NetBSD).
# The guard below only runs under GNU make; BSD make fails earlier.
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
RAYLIB_API  := $(RAYLIB_DIR)/tools/rlparser/output/raylib_api.lua
RLPARSER_DIR := $(RAYLIB_DIR)/tools/rlparser
RLPARSER     := $(RLPARSER_DIR)/rlparser
API_DIR      := $(RLPARSER_DIR)/output
BINDING      := hate-no-d.lua
OBJ         := hate-no-d.o
BIN         := hate-no-d

# 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
  # raylib's own BSD list lacks the X11 set its examples link.
  PLAT_LIBS      := -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.
#
# 64-bit targets build on any 64-bit host. i686 also needs a 32-bit host
# compiler, because LuaJIT's buildvm runs natively and its pointer size must
# match the target:
#   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, so label both to the sub-make: otherwise
  # the host tools (minilua, buildvm) are compiled 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 only stops
# -dead_strip / LTO from discarding the Lua API. GC64 is mandatory on arm64.
# JIT under the hardened runtime needs MAP_JIT, which is compiled in only when
# the deployment target is >= 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 therefore notarization).
  # Requires MACOSX_DEPLOYMENT_TARGET >= 11.0 or LuaJIT compiles it back out.
  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 above
# already pins gcc; everywhere else 'cc' is the native compiler.
HOST_CC ?= cc
LUAJIT  ?= luajit

# raylib's RELEASE desktop build appends -O1. -O2 is a large win for CPU-bound
# code (measured 0.83s -> 0.47s on image generation here); -O3 adds nothing.
# Override with RAYLIB_OPT=..., then run `make clean` (objects are not
# flag-aware, so raylib will not rebuild by itself).
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 because its Makefile defaults to
# native 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 artifacts, submodules included"
	@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)

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

# raylib must be pulled in whole: nothing references it, so the linker would
# otherwise 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)
#
# rlparser emits plain Lua tables; gen-hate-no-d.lua turns raylib.h + rlgl.h +
# raymath.h into one ffi.cdef block, constants, wrappers and LuaCATS comments.
# The tables live in raylib's own tools output directory, next to the committed
# raylib_api.lua; there is no second copy of the parser in this repo.
#
# rlparser is built for the host with HOST_CC, never with the target CC: cross
# builds still have to execute it while generating the platform-independent
# hate-no-d.lua.
# ---------------------------------------------------------------------------
# raylib gitignores this binary; its own Makefile builds it in place when a
# fresh checkout does not have one yet. CFLAGS is pinned so a cross/target
# build's command-line flags never leak into the host tool.
$(RLPARSER): $(RLPARSER_DIR)/rlparser.c
	$(MAKE) -C $(RLPARSER_DIR) CC="$(HOST_CC)" CFLAGS="-O2 -Wall -std=c99" rlparser

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

$(API_DIR)/raymath_api.lua: $(RLPARSER) $(RAYLIB_SRC)/raymath.h
	$(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=$@

bindings: $(BINDING)

# Fail if regeneration is not byte-identical or the module does not load; also
# checks the three API families are present.
check-bindings: $(BINDING)
	$(LUAJIT) gen-hate-no-d.lua --out=hate-no-d.lua.tmp
	cmp $(BINDING) hate-no-d.lua.tmp
	rm -f 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")'

# Show the resolved configuration for the current (or selected) platform.
# Useful for checking a cross build before committing to it.
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 "LINK_TARGET              = $(LINK_TARGET)"
	@echo "OBJ                      = $(OBJ)"
	@echo "HOST_CC                  = $(HOST_CC)"
	@echo "LUAJIT                   = $(LUAJIT)"
	@echo "API_DIR                  = $(API_DIR)"
	@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 -f $(BIN) hate-no-d.exe $(OBJ) libhate-no-d.a libhate-no-d.a.mri $(LUAJIT_AR) $(RAYLIB_AR)
	rm -f $(BINDING) hate-no-d.lua.tmp
	rm -f $(API_DIR)/rlgl_api.lua $(API_DIR)/raymath_api.lua

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