# C-Relay Makefile

CC = gcc
CFLAGS = -Wall -Wextra -std=c99 -g -O2
INCLUDES = -I. -Ic_utils_lib/src -Inostr_core_lib -Inostr_core_lib/nostr_core -Inostr_core_lib/cjson -Inostr_core_lib/nostr_websocket
LIBS = -lsqlite3 -lwebsockets -lz -ldl -lpthread -lm -L/usr/local/lib -lsecp256k1 -lssl -lcrypto -L/usr/local/lib -lcurl -Lc_utils_lib -lc_utils

# Build directory
BUILD_DIR = build

# Source files
MAIN_SRC = src/main.c src/config.c src/dm_admin.c src/request_validator.c src/nip009.c src/nip011.c src/nip013.c src/nip040.c src/nip042.c src/websockets.c src/subscriptions.c src/api.c src/embedded_web_content.c src/ip_ban.c src/db_ops.c src/thread_pool.c
NOSTR_CORE_LIB = nostr_core_lib/libnostr_core_x64.a
C_UTILS_LIB = c_utils_lib/libc_utils.a

# Architecture detection
ARCH = $(shell uname -m)
ifeq ($(ARCH),x86_64)
    TARGET = $(BUILD_DIR)/c_relay_x86
else ifeq ($(ARCH),aarch64)
    TARGET = $(BUILD_DIR)/c_relay_arm64
else ifeq ($(ARCH),arm64)
    TARGET = $(BUILD_DIR)/c_relay_arm64
else
    TARGET = $(BUILD_DIR)/c_relay_$(ARCH)
endif

# Default target
all: $(TARGET)

# Create build directory
$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)

# Check if nostr_core_lib is built
# Explicitly specify NIPs to ensure NIP-44 (encryption) is included
# NIPs: 1 (basic), 6 (keys), 13 (PoW), 17 (DMs), 19 (bech32), 44 (encryption), 59 (gift wrap)
$(NOSTR_CORE_LIB):
	@echo "Building nostr_core_lib with required NIPs (including NIP-44 for encryption)..."
	cd nostr_core_lib && ./build.sh --nips=1,6,13,17,19,44,59

# Check if c_utils_lib is built
$(C_UTILS_LIB):
	@echo "Building c_utils_lib..."
	cd c_utils_lib && ./build.sh lib

# Update main.h version information (requires main.h to exist)
src/main.h:
	@if [ ! -f src/main.h ]; then \
		echo "ERROR: src/main.h not found!"; \
		echo "Please ensure src/main.h exists with relay metadata."; \
		echo "Copy from a backup or create manually with proper relay configuration."; \
		exit 1; \
	fi; \
	if [ -d .git ]; then \
		echo "Updating main.h version information from git tags..."; \
		RAW_VERSION=$$(git describe --tags --always 2>/dev/null || echo "unknown"); \
		if echo "$$RAW_VERSION" | grep -q "^v[0-9]"; then \
			CLEAN_VERSION=$$(echo "$$RAW_VERSION" | sed 's/^v//' | cut -d- -f1); \
			VERSION="v$$CLEAN_VERSION"; \
			MAJOR=$$(echo "$$CLEAN_VERSION" | cut -d. -f1); \
			MINOR=$$(echo "$$CLEAN_VERSION" | cut -d. -f2); \
			PATCH=$$(echo "$$CLEAN_VERSION" | cut -d. -f3); \
		else \
			VERSION="v0.0.0"; \
			MAJOR=0; MINOR=0; PATCH=0; \
		fi; \
		echo "Updating version information in existing main.h..."; \
		sed -i "s/#define VERSION \".*\"/#define VERSION \"$$VERSION\"/g" src/main.h; \
		sed -i "s/#define VERSION_MAJOR [0-9]*/#define VERSION_MAJOR $$MAJOR/g" src/main.h; \
		sed -i "s/#define VERSION_MINOR [0-9]*/#define VERSION_MINOR $$MINOR/g" src/main.h; \
		sed -i "s/#define VERSION_PATCH [0-9]*/#define VERSION_PATCH $$PATCH/g" src/main.h; \
		echo "Updated main.h version to: $$VERSION"; \
	else \
		echo "Git not available, preserving existing main.h version information"; \
	fi

# Update main.h version information (requires existing main.h)
force-version:
	@echo "Force updating main.h version information..."
	@$(MAKE) src/main.h

# Build the relay
$(TARGET): $(BUILD_DIR) src/main.h src/sql_schema.h $(MAIN_SRC) $(NOSTR_CORE_LIB) $(C_UTILS_LIB)
	@echo "Compiling C-Relay for architecture: $(ARCH)"
	$(CC) $(CFLAGS) $(INCLUDES) $(MAIN_SRC) -o $(TARGET) $(NOSTR_CORE_LIB) $(C_UTILS_LIB) $(LIBS)
	@echo "Build complete: $(TARGET)"

# Build for specific architectures
x86: $(BUILD_DIR) src/main.h src/sql_schema.h $(MAIN_SRC) $(NOSTR_CORE_LIB) $(C_UTILS_LIB)
	@echo "Building C-Relay for x86_64..."
	$(CC) $(CFLAGS) $(INCLUDES) $(MAIN_SRC) -o $(BUILD_DIR)/c_relay_x86 $(NOSTR_CORE_LIB) $(C_UTILS_LIB) $(LIBS)
	@echo "Build complete: $(BUILD_DIR)/c_relay_x86"


# Check local build tooling used by static Docker builder
check-toolchain:
	@echo "Checking available toolchains:"
	@echo "Native compiler: $(shell $(CC) --version | head -1)"
	@if command -v docker >/dev/null 2>&1; then \
		echo "Docker: $$(docker --version)"; \
	else \
		echo "Docker: NOT INSTALLED"; \
	fi
	@if docker buildx version >/dev/null 2>&1; then \
		echo "Docker buildx: AVAILABLE"; \
	else \
		echo "Docker buildx: NOT AVAILABLE (required for cross-architecture static builds)"; \
	fi

# Run tests
test: $(TARGET)
	@echo "Running tests..."
	./tests/1_nip_test.sh

# Initialize database (now handled automatically when server starts)
init-db:
	@echo "Database initialization is now handled automatically when the server starts."
	@echo "The schema is embedded in the binary - no external files needed."
	@echo "To manually recreate database: rm -f db/c_nostr_relay.db && ./build/c_relay_x86"

# Clean build artifacts
clean:
	rm -rf $(BUILD_DIR)
	@echo "Clean complete"

# Clean everything including nostr_core_lib and c_utils_lib
clean-all: clean
	cd nostr_core_lib && make clean 2>/dev/null || true
	cd c_utils_lib && make clean 2>/dev/null || true

# Install dependencies (Ubuntu/Debian)
install-deps:
	@echo "Installing dependencies..."
	sudo apt update
	sudo apt install -y build-essential libsqlite3-dev libssl-dev libcurl4-openssl-dev libsecp256k1-dev zlib1g-dev jq curl

# Help
help:
	@echo "C-Relay Build System"
	@echo ""
	@echo "Targets:"
	@echo "  all              Build the relay for current architecture (default)"
	@echo "  x86              Build specifically for x86_64"
	@echo "  static-musl-x86_64 Build static MUSL binary using Docker (host arch default)"
	@echo "  static-musl-arm64 Build static MUSL ARM64 binary using Docker buildx"
	@echo "  static-musl      Build both static MUSL binaries"
	@echo "  test             Build and run tests"
	@echo "  init-db          Initialize the database"
	@echo "  clean            Clean build artifacts"
	@echo "  clean-all        Clean everything including dependencies"
	@echo "  install-deps     Install system dependencies"
	@echo "  check-toolchain  Check available local tooling"
	@echo "  help             Show this help"
	@echo ""
	@echo "Usage:"
	@echo "  make                     # Build the relay for current arch"
	@echo "  make x86                 # Build for x86_64"
	@echo "  make static-musl-x86_64  # Build static binary via ./build_static.sh"
	@echo "  make static-musl-arm64   # Build ARM64 static binary via ./build_static.sh --arch arm64"
	@echo "  make static-musl         # Build both static binaries"
	@echo "  make check-toolchain     # Check docker/buildx availability"
	@echo "  make test                # Run tests"
	@echo "  make init-db             # Set up database"
	@echo "  make force-version       # Force regenerate main.h from git"

# Build fully static MUSL binaries using Docker
static-musl-x86_64:
	@echo "Building fully static MUSL binary using host architecture default..."
	./build_static.sh
	@echo "Static binary created in build/ (host architecture naming)"

static-musl-arm64:
	@echo "Building fully static MUSL binary for ARM64..."
	./build_static.sh --arch arm64
	@echo "Static ARM64 binary created in build/"

static-musl: static-musl-x86_64 static-musl-arm64
	@echo "Built static MUSL binaries for both architectures"

.PHONY: static-musl-x86_64 static-musl-arm64 static-musl
.PHONY: all x86 test init-db clean clean-all install-deps check-toolchain help force-version