CROSS_COMPILE ?= 
CC := $(CROSS_COMPILE)gcc
STRIP := $(CROSS_COMPILE)strip
CFLAGS += -g -Wall -Iip2region
LIBS = 
BIN := denyip


# 检测操作系统并设置相应的变量
OS := $(shell if cat /etc/issue | grep -i 'ubuntu' >/dev/null 2>&1; then \
            echo ubuntu; \
        elif test -f /etc/debian_version; then \
            echo debian; \
        elif test -f /etc/centos-release; then \
            echo centos; \
        else \
            echo unsupported; \
        fi)

OS_VER := $(shell if [ "$(OS)" = "ubuntu" ]; then \
               cat /etc/issue | head -n1 | awk '{print $$2}'; \
           elif [ "$(OS)" = "debian" ]; then \
               cat /etc/debian_version; \
           elif [ "$(OS)" = "centos" ]; then \
               cat /etc/centos-release | grep -o -E '[0-9.]{3,}' 2>/dev/null; \
           else \
               echo "N/A"; \
           fi)

KERNEL := $(shell uname -sr)
ARCH := $(shell uname -m)



# 使用shell命令获取库的链接选项
ifeq ($(OS), centos)
	LIBPCAP := /usr/lib64/libpcap.so
	LIBS = 
else
	LIBPCAP := $(shell pkg-config --libs --static libpcap)
endif
LIBCAP := $(shell pkg-config --libs --static libcap)
LIBIPSET := $(shell pkg-config --libs --static libipset)

CFLAGS_LIBCURL += -DCURL_STATICLIB -I./libcurl/include
LIBCURL := -L./libcurl/lib -lcurl -lssh2 -lssh2 -lgpg-error -lssl -ldl -lcrypto -ldl -lz -lssl -lcrypto -lssl -ldl -pthread -lcrypto -ldl -pthread -lzstd -lz

CFLAGS_LIBCJSON += -I./libcjson/include/
LIBCJSON := ./libcjson/lib/libcjson.a 

all: $(BIN)  # 默认目标

# 系统信息打印目标
info:
	@echo "Operating System: $(OS)"
	@echo "OS Version: $(OS_VER)"
	@echo "Kernel Version: $(KERNEL)"
	@echo "Architecture: $(ARCH)"
	@echo "Compiler: $(CC)"
	@echo "CFLAGS: $(CFLAGS)"
	@echo "Libraries: $(LIBS)"
	@echo "LIBPCAP: $(LIBPCAP)"
	@echo "LIBCAP: $(LIBCAP)"
	@echo "LIBIPSET: $(LIBIPSET)"

# Go 构建目标
ipquery:
	cd IP_region_query && CGO_ENABLED=0 go build -ldflags '-w -s' && upx -9 ipquery

# 动态链接目标
$(BIN): cap.o common.o ip2region/ip2region.o ip2region/xdb_searcher.o libipset.o libcurl.o
	$(CC) $(CFLAGS) -o $(BIN) $^ -lpcap -lipset -lcurl -lcjson

# 静态链接目标
static: cap.o common.o ip2region/ip2region.o ip2region/xdb_searcher.o libipset.o libcurl.o
	$(CC) $(CFLAGS) $(CFLAGS_LIBCURL) $(CFLAGS_LIBCJSON) -o $(BIN) $^ $(LIBPCAP) $(LIBCAP) $(LIBIPSET) $(LIBCJSON)  $(LIBCURL) $(LIBS) -static

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

# 清理目标
clean:
	rm -rf $(BIN) IP_region_query/ipquery
	rm -rf cap.o common.o ip2region/ip2region.o ip2region/xdb_searcher.o libipset.o libcurl.o
