# 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.

SAN      ?= 1
HOSTCC    = gcc
ROOT      = ../../..
OBJDIR    = $(ROOT)/obj/host
BINDIR    = $(OBJDIR)/test
LIBDVX    = $(ROOT)/src/libs/kpunch/libdvx
LIBTASKS  = $(ROOT)/src/libs/kpunch/libtasks
WIDGETS   = $(ROOT)/src/widgets/kpunch
WIDGETDIR = $(OBJDIR)/widgets

CFLAGS    = -O1 -g -Wall -Wextra -Werror -Wno-type-limits -Wno-sign-compare -Wno-format-truncation -D_GNU_SOURCE -I$(LIBDVX) -I$(LIBDVX)/platform -I$(LIBDVX)/thirdparty -I$(LIBTASKS) -I$(WIDGETS)
LDFLAGS   = -rdynamic
LDLIBS    = -ldl -lm
ifeq ($(SAN),1)
CFLAGS   += -fsanitize=address,undefined -fno-omit-frame-pointer
LDFLAGS  += -fsanitize=address,undefined
endif

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

.PHONY: all run libs clean

all: run

libs:
	$(MAKE) -C $(LIBDVX) host SAN=$(SAN)
	$(MAKE) -C $(LIBTASKS) host SAN=$(SAN)
	$(MAKE) -C $(WIDGETS) host SAN=$(SAN)

$(TARGET): smoke.c libs
	@mkdir -p $(BINDIR)
	$(HOSTCC) $(CFLAGS) $(LDFLAGS) -o $@ smoke.c -Wl,--whole-archive $(OBJDIR)/libdvx.a $(OBJDIR)/libtasks.a -Wl,--no-whole-archive $(LDLIBS)

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

clean:
	rm -rf $(BINDIR)
	$(MAKE) -C $(LIBDVX) host-clean
	$(MAKE) -C $(LIBTASKS) host-clean
	$(MAKE) -C $(WIDGETS) host-clean
