# Makefile for ifone NIF

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

# Compiler flags
CC = cc
CFLAGS = -O2 -Wall -Wextra -Wno-unused-parameter -fPIC -I$(ERLANG_PATH)

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

ifeq ($(UNAME_S),Darwin)
    # macOS
    LDFLAGS = -dynamiclib -undefined dynamic_lookup
    LDFLAGS += -framework IOKit -framework CoreFoundation
    SO_EXT = so
else ifeq ($(UNAME_S),Linux)
    # Linux
    LDFLAGS = -shared
    SO_EXT = so
else
    $(error Unsupported platform: $(UNAME_S))
endif

# Directories - use MIX_APP_PATH from elixir_make to build directly to _build/
PRIV_DIR = $(MIX_APP_PATH)/priv
C_SRC_DIR = c_src

# Files
NIF_SRC = $(C_SRC_DIR)/ifone_nif.c
NIF_SO = $(PRIV_DIR)/ifone_nif.$(SO_EXT)

.PHONY: all clean

all: $(NIF_SO)

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

$(NIF_SO): $(NIF_SRC) | $(PRIV_DIR)
	$(CC) $(CFLAGS) $(NIF_SRC) -o $(NIF_SO) $(LDFLAGS)

clean:
	rm -f $(NIF_SO)
