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

# SecLink Proxy  -- Linux build
# Compiles the packet, security (with Monocypher), and secLink layers
# against a socket shim (sockShim.c implements the rs232 entry points they call) instead of
# the DJGPP rs232 driver.

include ../../common.mk

KPUNCH = ../../libs/kpunch
MONO   = $(KPUNCH)/crypto/thirdparty/monocypher/src
CFLAGS = $(HOST_TOOL_CFLAGS) -I$(MONO)

OBJDIR = ../../../obj/proxy
BINDIR = ../../../bin/host

TARGET = $(BINDIR)/secproxy

SRCS = sockShim.c proxy.c $(KPUNCH)/seclink/packet.c $(KPUNCH)/crypto/secCurve.c $(KPUNCH)/crypto/secHash.c $(KPUNCH)/crypto/security.c $(MONO)/monocypher.c $(KPUNCH)/seclink/secLink.c
OBJS = $(patsubst %.c,$(OBJDIR)/%.o,$(notdir $(SRCS)))

.PHONY: all clean

all: $(TARGET)

# Uses HOSTCC (not CC, which common.mk points at the DOS cross compiler).
$(TARGET): $(OBJS) | $(BINDIR)
	$(HOSTCC) -o $@ $(OBJS)

# One object rule per source: the local shim and proxy plus the shared
# seclink and crypto library sources, compiled unmodified except that sockShim.h is
# force-included (its wall-clock clock(), see there).
define PROXY_OBJ_RULE
$(OBJDIR)/$(basename $(notdir $1)).o: $1 $$(DVX_MAKEFILES) | $$(OBJDIR)
	$$(HOSTCC) $$(CFLAGS) -include sockShim.h -c -o $$@ $$<
endef

$(foreach src,$(SRCS),$(eval $(call PROXY_OBJ_RULE,$(src))))

$(OBJDIR) $(BINDIR):
	mkdir -p $@

-include $(OBJS:.o=.d)

clean:
	rm -rf $(OBJDIR) $(TARGET)
