# The MIT License (MIT)
#
# Copyright (C) 2026 Scott Duensing
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

# Host-side smoke test for the native platform backend.
#
# Builds obj/host/libdvx.a, obj/host/libtasks.a and every widget .so with
# the host toolchain, links smoke.c against them with -rdynamic so the
# dlopen'd widgets resolve core symbols from the executable, then runs it.
# Sanitizers are on by default (SAN=1); pass SAN=0 for a plain build.

include ../../common.mk

ROOT      = ../../..
OBJDIR    = $(HOST_OBJROOT)
BINDIR    = $(OBJDIR)/test
LIBDVX    = $(ROOT)/src/libs/kpunch/libdvx
LIBTASKS  = $(ROOT)/src/libs/kpunch/libtasks
WIDGETS   = $(ROOT)/src/widgets/kpunch
WIDGETDIR = $(OBJDIR)/widgets
LIBDVX_A  = $(OBJDIR)/libdvx.a
TASKS_A   = $(OBJDIR)/libtasks.a

CFLAGS    = $(HOST_CFLAGS) -I$(LIBDVX) -I$(LIBDVX)/platform -I$(LIBDVX)/thirdparty -I$(LIBTASKS) -I$(WIDGETS)
LDFLAGS   = -rdynamic $(HOST_LDFLAGS)
LDLIBS    = -ldl -lm

TARGET    = $(BINDIR)/smoke
PNG       = $(BINDIR)/smoke.png

.PHONY: all run widgets clean force

all: run

# The archives' sub-makes always run; make re-reads their time stamps, so
# smoke relinks exactly when a library changed.
$(LIBDVX_A): force
	$(MAKE) -C $(LIBDVX) host SAN=$(SAN)

$(TASKS_A): force
	$(MAKE) -C $(LIBTASKS) host SAN=$(SAN)

widgets:
	$(MAKE) -C $(WIDGETS) host SAN=$(SAN)

$(TARGET): smoke.c $(DVX_MAKEFILES) $(LIBDVX_A) $(TASKS_A) | widgets
	@mkdir -p $(BINDIR)
	$(HOSTCC) $(CFLAGS) $(LDFLAGS) -o $@ smoke.c -Wl,--whole-archive $(LIBDVX_A) $(TASKS_A) -Wl,--no-whole-archive $(LDLIBS)

-include $(TARGET).d

run: $(TARGET)
	cd $(BINDIR) && ASAN_OPTIONS=detect_leaks=1 ./smoke $(abspath $(WIDGETDIR)) $(abspath $(PNG))

clean:
	rm -f $(TARGET) $(TARGET).d $(PNG)
