# Makefile for check_ncpa
# Nagios NCPA check plugin written in C
#
# Requires: libcurl-devel, libcjson-devel

CC = gcc
CFLAGS = -Wall -Wextra -O2 -std=c99
LDFLAGS = -lcurl -lm

# Binary name
TARGET = check_ncpa

# Source files
SOURCES = check_ncpa.c

# Installation directory (adjust as needed)
INSTALL_DIR = /usr/local/nagios/libexec

# Require system libcjson
CJSON_OK := $(shell pkg-config --exists libcjson 2>/dev/null && echo "yes" || echo "no")
ifeq ($(CJSON_OK),yes)
    CFLAGS += $(shell pkg-config --cflags libcjson)
    LDFLAGS += $(shell pkg-config --libs libcjson)
else
    $(error libcjson not found. Install it: apt-get install libcjson-dev OR yum install cjson-devel)
endif

.PHONY: all clean install uninstall help test-compile

all: $(TARGET)

$(TARGET): $(SOURCES)
	@echo "==> Compiling $(TARGET)..."
	$(CC) $(CFLAGS) -o $(TARGET) $(SOURCES) $(LDFLAGS)
	@echo "==> Build successful!"
	@echo ""
	@echo "Usage: ./$(TARGET) -H <hostname> -M <metric> -t <token>"
	@echo "       ./$(TARGET) --help"

install: $(TARGET)
	@echo "==> Installing $(TARGET) to $(INSTALL_DIR)..."
	install -d $(INSTALL_DIR)
	install -m 0755 $(TARGET) $(INSTALL_DIR)/
	@echo "==> Installation complete!"
	@echo "Installed to: $(INSTALL_DIR)/$(TARGET)"

uninstall:
	@echo "==> Uninstalling $(TARGET) from $(INSTALL_DIR)..."
	rm -f $(INSTALL_DIR)/$(TARGET)
	@echo "==> Uninstall complete!"

clean:
	@echo "==> Cleaning build artifacts..."
	rm -f $(TARGET) *.o
	@echo "==> Clean complete!"

test-compile: clean all
	@echo "==> Test compilation successful!"

help:
	@echo "Makefile for check_ncpa (Nagios NCPA check plugin)"
	@echo ""
	@echo "Targets:"
	@echo "  all             - Build the check_ncpa binary (default)"
	@echo "  clean           - Remove compiled binaries and object files"
	@echo "  install         - Install binary to $(INSTALL_DIR)"
	@echo "  uninstall       - Remove installed binary"
	@echo "  test-compile    - Clean and rebuild to test compilation"
	@echo "  help            - Display this help message"
	@echo ""
	@echo "Dependencies:"
	@echo "  - libcurl-devel  (apt-get install libcurl4-openssl-dev / yum install libcurl-devel)"
	@echo "  - libcjson-devel (apt-get install libcjson-dev / yum install cjson-devel)"
	@echo ""
	@echo "Variables:"
	@echo "  INSTALL_DIR     - Installation directory (default: $(INSTALL_DIR))"
	@echo "  CC              - C compiler (default: $(CC))"
	@echo "  CFLAGS          - Compiler flags (default: $(CFLAGS))"
	@echo ""
	@echo "Example:"
	@echo "  make clean"
	@echo "  make"
	@echo "  sudo make install INSTALL_DIR=/usr/lib64/nagios/plugins"
