# Host tests for the script sockets (main/wifi/script_tcp.c) and their Lua
# bindings (main/script/lua_vesc_tcp.c), against real servers on 127.0.0.1
# (tls_server.py) and the host's mbedTLS 4. Run from tests/check.sh.
#
# Twice: as the host's mbedTLS is configured, and with the max fragment
# length forced to 1 kB, as a C3 build asks for it (its record buffers are
# 1 kB). The TLS timeout is 2 s here so the silent-server case is quick.

CFLAGS += -O1 -g -std=gnu11 -Wall -Wextra
SAN ?= -fsanitize=address,undefined -fno-omit-frame-pointer

MAIN = ../../main
LUA_DIR = $(MAIN)/lua
INCLUDES = -I$(MAIN)/wifi -I$(MAIN)/script -I$(LUA_DIR) -DLUA_USE_APICHECK
LIBS = -lmbedtls -lmbedx509 -lmbedcrypto -lpthread -lm

SRCS = test_script_tcp.c $(MAIN)/wifi/script_tcp.c $(MAIN)/script/lua_vesc_tcp.c \
	$(MAIN)/script/script_lua.c $(MAIN)/script/script_pack.c
HDRS = $(MAIN)/wifi/script_tcp.h $(MAIN)/script/lua_vesc_ext.h

LUA_SRCS = $(wildcard $(LUA_DIR)/*.c)

all: test_script_tcp test_script_tcp_mfl

# Vendored Lua, without our warning flags, as main/script/test builds it.
lua_objs.a: $(LUA_SRCS) $(wildcard $(LUA_DIR)/*.h)
	@mkdir -p .luaobj
	@for f in $(LUA_SRCS); do \
		$(CC) -O1 -g -std=c11 -I$(LUA_DIR) -DLUA_USE_APICHECK $(SAN) -c $$f \
			-o .luaobj/`basename $$f .c`.o || exit 1; \
	done
	@$(AR) rcs $@ .luaobj/*.o

test_script_tcp: $(SRCS) $(HDRS) lua_objs.a
	$(CC) $(CFLAGS) $(SAN) $(INCLUDES) -DSCRIPT_TCP_TLS_TIMEOUT_S=2 -DSCRIPT_TCP_CONNECT_TIMEOUT_MS=1000 -DSCRIPT_TCP_MFL=0 \
		-o $@ $(SRCS) lua_objs.a $(LIBS)

test_script_tcp_mfl: $(SRCS) $(HDRS) lua_objs.a
	$(CC) $(CFLAGS) $(SAN) $(INCLUDES) -DSCRIPT_TCP_TLS_TIMEOUT_S=2 -DSCRIPT_TCP_CONNECT_TIMEOUT_MS=1000 -DSCRIPT_TCP_MFL=2 \
		-o $@ $(SRCS) lua_objs.a $(LIBS)

run: all
	./test_script_tcp .
	./test_script_tcp_mfl .

clean:
	rm -f test_script_tcp test_script_tcp_mfl lua_objs.a
	rm -rf .luaobj

.PHONY: all run clean
