# Ginxsom Blossom Server Makefile

CC = gcc
CFLAGS = -Wall -Wextra -std=gnu99 -O2 -Inostr_core_lib/nostr_core -Inostr_core_lib/cjson
LIBS = -lfcgi -lsqlite3 nostr_core_lib/libnostr_core_x64.a -lz -ldl -lpthread -lm -L/usr/local/lib -lsecp256k1 -lssl -lcrypto -lcurl
SRCDIR = src
BUILDDIR = build
TARGET = $(BUILDDIR)/ginxsom-fcgi

# Source files
SOURCES = $(SRCDIR)/main.c $(SRCDIR)/admin_api.c $(SRCDIR)/admin_auth.c $(SRCDIR)/admin_event.c $(SRCDIR)/admin_handlers.c $(SRCDIR)/admin_interface.c $(SRCDIR)/bud04.c $(SRCDIR)/bud06.c $(SRCDIR)/bud08.c $(SRCDIR)/bud09.c $(SRCDIR)/request_validator.c $(SRCDIR)/relay_client.c $(SRCDIR)/admin_commands.c
OBJECTS = $(SOURCES:$(SRCDIR)/%.c=$(BUILDDIR)/%.o)

# Embedded web interface files
EMBEDDED_HEADER = $(SRCDIR)/admin_interface_embedded.h
EMBED_SCRIPT = scripts/embed_web_files.sh

# Add core_relay_pool.c from nostr_core_lib
POOL_SRC = nostr_core_lib/nostr_core/core_relay_pool.c
POOL_OBJ = $(BUILDDIR)/core_relay_pool.o

# Default target
all: $(EMBEDDED_HEADER) $(TARGET)

# Generate embedded web interface files
$(EMBEDDED_HEADER): $(EMBED_SCRIPT) api/*.html api/*.css api/*.js
	@echo "Embedding web interface files..."
	@$(EMBED_SCRIPT)

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

# Compile object files
$(BUILDDIR)/%.o: $(SRCDIR)/%.c | $(BUILDDIR)
	$(CC) $(CFLAGS) -c $< -o $@

# Compile core_relay_pool.o (needs src/ for request_validator.h)
$(POOL_OBJ): $(POOL_SRC) | $(BUILDDIR)
	$(CC) $(CFLAGS) -I$(SRCDIR) -c $< -o $@

# Link final executable
$(TARGET): $(OBJECTS) $(POOL_OBJ)
	$(CC) $(OBJECTS) $(POOL_OBJ) $(LIBS) -o $@

# Clean build files
clean:
	rm -rf $(BUILDDIR)
	rm -f $(EMBEDDED_HEADER)

# Install (copy to system location)
install: $(TARGET)
	sudo cp $(TARGET) /usr/local/bin/
	sudo chmod 755 /usr/local/bin/ginxsom-fcgi

# Uninstall
uninstall:
	sudo rm -f /usr/local/bin/ginxsom-fcgi

# Run the FastCGI application
run: $(TARGET)
	./$(TARGET)

# Debug build
debug: CFLAGS += -g -DDEBUG
debug: $(TARGET)

# Rebuild embedded files
embed:
	@$(EMBED_SCRIPT)

.PHONY: all clean install uninstall run debug embed
