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


# Form-runtime test suite (T5): formrt + basrt on the host backend.
#
#     make -C src/test/formrt          # build + run (SAN=1 default)
#     make -C src/test/formrt SAN=0
#
# Links obj/host/basrt.a (compiler + runtime + formrt, built by the
# dvxbasic Makefile's host-basrt target) with libdvx.a, libdvxtest.a
# and the widget .so files.

.DEFAULT_GOAL := all

include ../dvxtest/dvxtest.mk

DVXBASIC   = $(DVXTEST_ROOT)/src/apps/kpunch/dvxbasic
BASRT_LIB  = $(DVXTEST_OBJDIR)/basrt.a
BINDIR     = $(DVXTEST_BINDIR)/formrt
TARGET     = $(BINDIR)/testFormRt
STUBS_SO   = $(BINDIR)/frtStubs.so
SRCS       = testFormRt.c frtHarness.c
OBJS       = $(patsubst %.c,$(BINDIR)/%.o,$(SRCS))
CFLAGS     = $(DVXTEST_CFLAGS) -I$(DVXBASIC) -I$(DVXTEST_ROOT)/src/libs/kpunch/dvxshell -DFRT_FIXTURE_DIR='"$(abspath .)/fixtures"' -DFRT_STUBS_SO='"$(abspath $(STUBS_SO))"'

.PHONY: all run libs clean

all: run

libs:
	$(MAKE) -f $(DVXTEST_DIR)/dvxtest.mk dvxtest-libs SAN=$(SAN)
	$(MAKE) -C $(DVXBASIC) host-basrt SAN=$(SAN)

BAS_HDRS   = $(wildcard $(DVXBASIC)/*.h $(DVXBASIC)/*/*.h)

$(BINDIR)/%.o: %.c frtHarness.h frtStubs.h $(BAS_HDRS) | libs
	@mkdir -p $(BINDIR)
	$(HOSTCC) $(CFLAGS) -c -o $@ $<

$(STUBS_SO): frtStubs.c frtStubs.h | libs
	@mkdir -p $(BINDIR)
	$(HOSTCC) $(CFLAGS) -fPIC -shared -o $@ frtStubs.c

$(TARGET): $(OBJS) $(STUBS_SO) | libs
	$(HOSTCC) -o $@ $(OBJS) $(BASRT_LIB) $(DVXTEST_LINK)

run: $(TARGET)
	ASAN_OPTIONS=detect_leaks=1 $(TARGET)

clean:
	rm -rf $(BINDIR)
