# Host build of the portable protocol core and its tests (macOS clang or Linux gcc).
# Needs libsodium (brew install libsodium) and, for nchost over wss://, OpenSSL 3.
#   make            build everything
#   make test       run the offline tests (vectors, NIP-59, signatures, framing, Papernet rules, power and bench)
#   make interop    run the resilient-comms interop test (network, see interop.sh; PAPERNET=1 adds the app-control case)

SODIUM  ?= $(shell brew --prefix libsodium 2>/dev/null || echo /usr)
OPENSSL ?= $(shell brew --prefix openssl@3 2>/dev/null || echo /usr)
CC      ?= cc
CORE    := ../libraries/nostrcore/src
SECP    := ../libraries/secp256k1_vendor
CJSON   := ../vendor/cjson
PN      := ../libraries/pncore/src
B       := build

CFLAGS  := -std=c11 -O2 -g -Wall -Wextra -Wshadow -D_DEFAULT_SOURCE -D_DARWIN_C_SOURCE \
           -I$(CORE) -I$(PN) -I$(SECP) -I$(CJSON) -I$(SODIUM)/include -I. -I$(OPENSSL)/include
LDLIBS  := -L$(SODIUM)/lib -lsodium
TLSLIBS := -L$(OPENSSL)/lib -lssl -lcrypto

CORE_SRC := $(wildcard $(CORE)/*.c)
CORE_OBJ := $(patsubst $(CORE)/%.c,$(B)/core/%.o,$(CORE_SRC))
SECP_OBJ := $(B)/secp/sv_secp256k1.o $(B)/secp/sv_precomputed_ecmult.o $(B)/secp/sv_precomputed_ecmult_gen.o
LIB      := $(B)/libnostrcore.a
PN_SRC   := $(wildcard $(PN)/*.c)
PN_OBJ   := $(patsubst $(PN)/%.c,$(B)/pn/%.o,$(PN_SRC))

TESTS := $(B)/test_nip44 $(B)/test_protocol $(B)/test_papernet $(B)/test_rc_radio $(B)/test_power

all: $(LIB) $(TESTS) $(B)/nchost

$(B)/core/%.o: $(CORE)/%.c $(wildcard $(CORE)/*.h)
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -c $< -o $@

$(B)/pn/%.o: $(PN)/%.c $(wildcard $(PN)/*.h)
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -c $< -o $@

# Electrical round E1: power budget, bench patterns, SX126x frames (no crypto, no libsodium).
$(B)/test_power: tests/test_power.c $(PN_OBJ)
	$(CC) $(CFLAGS) $< $(PN_OBJ) -o $@

# Upstream code: compiled as is, warnings are upstream's business.
$(B)/secp/%.o: $(SECP)/%.c $(SECP)/sv_secp256k1_config.h
	@mkdir -p $(dir $@)
	$(CC) -std=c11 -O2 -g -w -c $< -o $@

$(B)/cJSON.o: $(CJSON)/cJSON.c
	@mkdir -p $(B)
	$(CC) -std=c11 -O2 -g -w -c $< -o $@

$(LIB): $(CORE_OBJ) $(SECP_OBJ) $(B)/cJSON.o
	ar rcs $@ $^

$(B)/test_%: tests/test_%.c $(LIB) kv_file.c
	$(CC) $(CFLAGS) $< kv_file.c -o $@ $(LIB) $(LDLIBS)

$(B)/nchost: nchost.c ws_client.c kv_file.c $(LIB)
	$(CC) $(CFLAGS) nchost.c ws_client.c kv_file.c -o $@ $(LIB) $(LDLIBS) $(TLSLIBS)

test: $(TESTS) $(B)/nchost
	./$(B)/test_nip44 ../vendor/nip44/nip44.vectors.json
	./$(B)/test_protocol
	./$(B)/test_papernet
	./$(B)/test_rc_radio ../vendor/rc_radio/vectors.json
	./$(B)/test_power
	./offline.sh

interop: $(B)/nchost
	./interop.sh

clean:
	rm -rf $(B)

.PHONY: all test interop clean
