# caching_relay Makefile - statically linked C99 binary, c-relay style

# Use bash for reliable glob expansion in recipes (dash handles globs differently).
SHELL := /bin/bash

CC = gcc
CFLAGS = -Wall -Wextra -std=c99 -g -O2

# nostr_core_lib is a sibling of c-relay-pg (one dir up from caching/).
NOSTR_CORE_DIR = ../nostr_core_lib

INCLUDES = -I. -Isrc -I$(NOSTR_CORE_DIR) -I$(NOSTR_CORE_DIR)/nostr_core \
           -I$(NOSTR_CORE_DIR)/cjson -I$(NOSTR_CORE_DIR)/nostr_websocket \
           -I/usr/include/postgresql

# -lsqlite3: nostr_core_lib's request_validator.x64.o references SQLite symbols;
# we use --whole-archive so the linker pulls in all objects (needed for NIP-42
# cross-references within the archive), which means SQLite must be satisfied.
# No c_utils_lib: nostr_core_lib does not depend on it for the NIPs we use.
# -lpq: PostgreSQL client library for the caching_event_inbox integration.
LIBS = -lwebsockets -lssl -lcrypto -lsecp256k1 -lcurl -lz -ldl -lpthread -lm -lpq -lsqlite3

MAIN_SRC = src/main.c src/debug.c src/jsonc_strip.c src/config.c src/state.c \
           src/follow_graph.c src/relay_sink.c src/live_subscriber.c \
           src/backfill.c src/relay_discovery.c \
           src/pg_inbox.c src/pg_config.c

# Architecture detection
ARCH = $(shell uname -m)
ifeq ($(ARCH),x86_64)
    NOSTR_CORE_LIB = $(NOSTR_CORE_DIR)/libnostr_core_x64.a
else ifeq ($(ARCH),aarch64)
    NOSTR_CORE_LIB = $(NOSTR_CORE_DIR)/libnostr_core_arm64.a
else ifeq ($(ARCH),arm64)
    NOSTR_CORE_LIB = $(NOSTR_CORE_DIR)/libnostr_core_arm64.a
else
    NOSTR_CORE_LIB = $(NOSTR_CORE_DIR)/libnostr_core_x64.a
endif

# Binary goes in the c-relay-pg build/ directory so the launcher can find it.
TARGET = ../build/caching_relay

all: $(TARGET)

# Build nostr_core_lib with the NIPs needed by the relay pool + signer:
# 1 (basic), 6 (keys), 19 (npub bech32), 4 (legacy encryption, signer dep),
# 42 (auth, relay pool dep), 44 (modern encryption, signer dep)
$(NOSTR_CORE_LIB):
	@echo "Building nostr_core_lib with required NIPs..."
	cd $(NOSTR_CORE_DIR) && ./build.sh --nips=1,4,6,19,42,44

$(TARGET): $(MAIN_SRC) $(NOSTR_CORE_LIB)
	@echo "Compiling caching_relay for architecture: $(ARCH)"
	@# Extract all objects from the static library and link them directly.
	@# This avoids archive symbol resolution ordering issues (NIP-42 cross-refs).
	@# Use a fixed temp dir and chain all commands with && so failures stop the build.
	@rm -rf /tmp/cr_lib && mkdir -p /tmp/cr_lib && \
	    ar x $(NOSTR_CORE_LIB) --output=/tmp/cr_lib && \
	    echo "Extracted $$(ls /tmp/cr_lib/*.o | wc -l) objects" && \
	    $(CC) $(CFLAGS) $(INCLUDES) $(MAIN_SRC) /tmp/cr_lib/*.o -o $(TARGET) $(LIBS) && \
	    rm -rf /tmp/cr_lib && \
	    echo "Build complete: $(TARGET)"

clean:
	rm -f $(TARGET)

.PHONY: all clean
