# =============================================================================
# MPPT Solar Charge Controller Monitor - Makefile
# =============================================================================
# Compatible with: Ubuntu 24.04 (x86_64) / Raspberry Pi 5 8G (aarch64)
#
# Libraries:
#   - mongoose-7.22  (HTTP server)
#   - cJSON-1.7.19   (JSON serialization)
#   - OpenSSL 3.x    (TLS support, optional)
#
# Usage:
#   make              - Build the project
#   make clean        - Remove build artifacts
#   make run          - Build and run
#   make debug        - Build with debug symbols and ASAN
#   make install      - Install to /usr/local/bin
#   make systemd      - Install systemd service file
# =============================================================================

# ── Compiler & Flags ─────────────────────────────────────────────
CC       ?= gcc
CFLAGS   := -Wall -Wextra -Wno-unused-parameter -O2 -g
LDFLAGS  := -lpthread -lm

# ── Directories ──────────────────────────────────────────────────
SRCDIR   := src
LIBDIR   := lib
BUILDDIR := build

# ── Library paths ────────────────────────────────────────────────
CJSON_DIR    := $(LIBDIR)/cJSON-1.7.19
MONGOOSE_DIR := $(LIBDIR)/mongoose-7.22

# ── Source files ─────────────────────────────────────────────────
APP_SRCS := $(SRCDIR)/main.c \
            $(SRCDIR)/modbus_client.c \
            $(SRCDIR)/web_server.c

LIB_SRCS := $(CJSON_DIR)/cJSON.c \
            $(MONGOOSE_DIR)/mongoose.c

ALL_SRCS := $(APP_SRCS) $(LIB_SRCS)

# ── Include paths ────────────────────────────────────────────────
INCLUDES := -I$(SRCDIR) \
            -I$(CJSON_DIR) \
            -I$(MONGOOSE_DIR)

# ── OpenSSL support ─────────────────────────────────────────────
# Auto-detect OpenSSL availability
OPENSSL_AVAILABLE := $(shell pkg-config --exists openssl 2>/dev/null && echo yes || echo no)

ifeq ($(OPENSSL_AVAILABLE),yes)
    CFLAGS  += -DMG_ENABLE_OPENSSL=1 $(shell pkg-config --cflags openssl)
    LDFLAGS += $(shell pkg-config --libs openssl)
else
    # Try manual paths (for Raspberry Pi or custom installs)
    OPENSSL_MANUAL := $(shell test -f /usr/include/openssl/ssl.h && echo yes || echo no)
    ifeq ($(OPENSSL_MANUAL),yes)
        CFLAGS  += -DMG_ENABLE_OPENSSL=1
        LDFLAGS += -lssl -lcrypto
    else
        # Check custom path from user's reference: /opt/openAI/Lib64U/
        OPENSSL_CUSTOM := $(shell test -f /opt/openAI/Lib64U/include/openssl/ssl.h && echo yes || echo no)
        ifeq ($(OPENSSL_CUSTOM),yes)
            CFLAGS  += -DMG_ENABLE_OPENSSL=1 -I/opt/openAI/Lib64U/include
            LDFLAGS += -L/opt/openAI/Lib64U/lib -lssl -lcrypto
        else
            $(warning OpenSSL not found - building without TLS support)
            $(warning Install with: sudo apt-get install libssl-dev)
        endif
    endif
endif

# ── Target ───────────────────────────────────────────────────────
TARGET := $(BUILDDIR)/mppt_monitor

# ── Object files ─────────────────────────────────────────────────
OBJS := $(patsubst %.c,$(BUILDDIR)/%.o,$(notdir $(ALL_SRCS)))

# ── Rules ────────────────────────────────────────────────────────
.PHONY: all clean run debug install systemd help

all: $(TARGET)

$(TARGET): $(OBJS)
	@mkdir -p $(BUILDDIR)
	$(CC) $(OBJS) -o $@ $(LDFLAGS)
	@echo "============================================"
	@echo "  Build complete: $(TARGET)"
	@echo "============================================"

# Compile source files - handle both src/ and lib/ directories
$(BUILDDIR)/main.o: $(SRCDIR)/main.c | $(BUILDDIR)
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

$(BUILDDIR)/modbus_client.o: $(SRCDIR)/modbus_client.c | $(BUILDDIR)
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

$(BUILDDIR)/web_server.o: $(SRCDIR)/web_server.c | $(BUILDDIR)
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

$(BUILDDIR)/cJSON.o: $(CJSON_DIR)/cJSON.c | $(BUILDDIR)
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

$(BUILDDIR)/mongoose.o: $(MONGOOSE_DIR)/mongoose.c | $(BUILDDIR)
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

$(BUILDDIR):
	@mkdir -p $(BUILDDIR)

# ── Debug build ──────────────────────────────────────────────────
debug: CFLAGS += -DDEBUG -fsanitize=address -fno-omit-frame-pointer
debug: LDFLAGS += -fsanitize=address
debug: clean all

# ── Run ──────────────────────────────────────────────────────────
run: all
	./$(TARGET)

# ── Clean ────────────────────────────────────────────────────────
clean:
	rm -rf $(BUILDDIR)

# ── Install ──────────────────────────────────────────────────────
install: all
	install -Dm755 $(TARGET) /usr/local/bin/mppt_monitor
	@echo "Installed to /usr/local/bin/mppt_monitor"

# ── Systemd service ──────────────────────────────────────────────
systemd: install
	@echo "Creating systemd service file..."
	@echo "[Unit]" > /etc/systemd/system/mppt-monitor.service
	@echo "Description=MPPT Solar Charge Controller Monitor" >> /etc/systemd/system/mppt-monitor.service
	@echo "After=network-online.target" >> /etc/systemd/system/mppt-monitor.service
	@echo "Wants=network-online.target" >> /etc/systemd/system/mppt-monitor.service
	@echo "" >> /etc/systemd/system/mppt-monitor.service
	@echo "[Service]" >> /etc/systemd/system/mppt-monitor.service
	@echo "Type=simple" >> /etc/systemd/system/mppt-monitor.service
	@echo "ExecStart=/usr/local/bin/mppt_monitor" >> /etc/systemd/system/mppt-monitor.service
	@echo "Restart=always" >> /etc/systemd/system/mppt-monitor.service
	@echo "RestartSec=5" >> /etc/systemd/system/mppt-monitor.service
	@echo "StandardOutput=journal" >> /etc/systemd/system/mppt-monitor.service
	@echo "StandardError=journal" >> /etc/systemd/system/mppt-monitor.service
	@echo "SyslogIdentifier=mppt-monitor" >> /etc/systemd/system/mppt-monitor.service
	@echo "" >> /etc/systemd/system/mppt-monitor.service
	@echo "[Install]" >> /etc/systemd/system/mppt-monitor.service
	@echo "WantedBy=multi-user.target" >> /etc/systemd/system/mppt-monitor.service
	@systemctl daemon-reload
	@systemctl enable mppt-monitor
	@echo "Systemd service installed and enabled."
	@echo "  Start:   sudo systemctl start mppt-monitor"
	@echo "  Status:  sudo systemctl status mppt-monitor"
	@echo "  Logs:    sudo journalctl -u mppt-monitor -f"

# ── Help ─────────────────────────────────────────────────────────
help:
	@echo "MPPT Monitor Build System"
	@echo ""
	@echo "  make          - Build the project"
	@echo "  make clean    - Remove build artifacts"
	@echo "  make run      - Build and run"
	@echo "  make debug    - Build with debug + ASAN"
	@echo "  make install  - Install to /usr/local/bin"
	@echo "  make systemd  - Install + setup systemd service"
	@echo "  make help     - Show this help"
	@echo ""
	@echo "OpenSSL: $(OPENSSL_AVAILABLE)"
	@echo "CC:      $(CC)"
