# Makefile for rtlsdr NIF
# Builds the native interface to librtlsdr

# Variables
PRIV_DIR = priv
NIF_SO = $(PRIV_DIR)/rtlsdr_nif.so

# Compiler settings
CC ?= cc
CFLAGS ?= -O2 -Wall -Wextra -fPIC

# Erlang paths
ERL_INCLUDE_PATH = $(shell erl -eval 'io:format("~s", [lists:concat([code:root_dir(), "/erts-", erlang:system_info(version), "/include"])])' -s init stop -noshell)

# Platform detection
UNAME_S := $(shell uname -s)

ifeq ($(UNAME_S),Darwin)
    # macOS
    LDFLAGS = -dynamiclib -undefined dynamic_lookup
    # Check for Homebrew installation of librtlsdr
    HOMEBREW_PREFIX := $(shell brew --prefix 2>/dev/null || echo "/usr/local")
    RTLSDR_INCLUDE ?= $(HOMEBREW_PREFIX)/include
    RTLSDR_LIB ?= $(HOMEBREW_PREFIX)/lib
else ifeq ($(UNAME_S),Linux)
    # Linux
    LDFLAGS = -shared
    RTLSDR_INCLUDE ?= /usr/include
    RTLSDR_LIB ?= /usr/lib
else
    $(error Unsupported platform: $(UNAME_S))
endif

# Include paths
CFLAGS += -I$(ERL_INCLUDE_PATH) -I$(RTLSDR_INCLUDE)

# Library paths
LDFLAGS += -L$(RTLSDR_LIB) -lrtlsdr -lpthread

# Source files
C_SRC = c_src/rtlsdr_nif.c

.PHONY: all clean

all: $(PRIV_DIR) $(NIF_SO)

$(PRIV_DIR):
	mkdir -p $(PRIV_DIR)

$(NIF_SO): $(C_SRC)
	$(CC) $(CFLAGS) $(C_SRC) -o $(NIF_SO) $(LDFLAGS)

clean:
	rm -rf $(PRIV_DIR)/*.so

# Installation check
check-deps:
	@echo "Checking for librtlsdr..."
	@pkg-config --exists librtlsdr && echo "librtlsdr found" || echo "librtlsdr NOT found - please install it"
	@echo "Checking for Erlang..."
	@which erl > /dev/null && echo "Erlang found at: $$(which erl)" || echo "Erlang NOT found"

# Debug build
debug: CFLAGS += -g -DDEBUG
debug: all
