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

# Cryptography Library Makefile for DJGPP cross-compilation
#
# crypto.lib: Diffie-Hellman, XTEA-CTR, the random number generator
# (security.c), SHA-256, HMAC and HKDF (secHash.c), X25519 and
# XChaCha20-Poly1305 (secCurve.c), Ed25519 (secSign.c), and their BASIC
# entry points (secBas.c, security.bas).  Monocypher (thirdparty) is
# built in; the library keeps only what its own objects reach of it
# (DXE_GC) and exports its own functions only.  The package library, the
# network, the shell's seed file, and the secure link use it.

include ../../../common.mk

MONO      = thirdparty/monocypher/src
CFLAGS    = $(DOS_CFLAGS) -I. -I$(MONO) -I../libdvx -I../libdvx/platform -I../libtasks

OBJDIR    = ../../../../obj/crypto
LIBSDIR   = ../../../../bin/libs

SRCS      = $(wildcard *.c)
OWN_OBJS  = $(patsubst %.c,$(OBJDIR)/%.o,$(SRCS))
MONO_OBJS = $(OBJDIR)/monocypher.o $(OBJDIR)/monocypher-ed25519.o
OBJS      = $(OWN_OBJS) $(MONO_OBJS)
GC_OBJ    = $(OBJDIR)/cryptoGc.o
TARGETDIR = $(LIBSDIR)/kpunch/crypto
TARGET    = $(TARGETDIR)/crypto.lib

vpath %.c . $(MONO) $(MONO)/optional

.PHONY: all clean

all: $(TARGET) $(TARGETDIR)/crypto.dep

$(TARGETDIR)/crypto.dep: crypto.dep | $(TARGETDIR)
	sed 's/$$/\r/' $< > $@

$(GC_OBJ): $(OBJS)
	$(DXE_GC) $@ $(OWN_OBJS) -- $(OBJS)

$(TARGET): $(GC_OBJ) | $(TARGETDIR)
	$(DXE3GEN) -o $(TARGETDIR)/crypto.dxe -U $(GC_OBJ)
	mv $(TARGETDIR)/crypto.dxe $@

$(OBJDIR)/%.o: %.c $(DVX_MAKEFILES) | $(OBJDIR)
	$(CC) $(CFLAGS) -c -o $@ $<

$(MONO_OBJS): $(OBJDIR)/%.o: %.c $(DVX_MAKEFILES) | $(OBJDIR)
	$(CC) $(CFLAGS) $(DXE_GC_CFLAGS) -c -o $@ $<

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

$(TARGETDIR):
	mkdir -p $(TARGETDIR)

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

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