# Define source file groups
set(src_apfreewifidog
	main.c gateway.c commandline.c conf.c debug.c
	firewall.c centralserver.c http.c auth.c client_list.c
	util.c wdctlx_thread.c ping_thread.c safe.c
	tls_thread.c wd_client.c wd_util.c mqtt_thread.c
	api_handlers_auth.c
	api_handlers_wifi.c
	api_handlers_sys.c
	hotplug_listener.c
	ws_thread.c api_handlers.c api_routes.c api_handlers_bpf.c api_handlers_vpn.c
	uci_helper.c
	client_snapshot.c dns_monitor.c
	client_library/shell_executor.c
	portal_cache.c
)

set(src_fw3
	fw_iptables.c fw3_iptc.c ipset.c
)

set(src_fw4
	fw_nft.c
)

set(src_vpp
	fw_vpp.c
)



set(src_wdctlx 
	wdctlx.c util.c debug.c
)

# Define common libraries
set(common_libs
	pthread m z json-c ssl crypto
	event event_openssl netfilter_queue
	resolv mosquitto uci
)

if(HAVE_LIBBPF)
	list(APPEND common_libs bpf)
endif()

# Set compiler flags
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall --std=gnu99 -Wmissing-declarations")
if(AW_DEBUG)
	set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ggdb")
	message(STATUS "Building in DEBUG mode")
else()
	set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O2")
	message(STATUS "Building in RELEASE mode")
endif()

# If libbpf was detected at configure time, expose a define so source
# can enable runtime features. Always build `dns_monitor.c` so the
# monitor thread can run and gracefully handle missing kernel maps.
if(HAVE_LIBBPF)
	message(STATUS "Configuring build with libbpf support")
	add_definitions(-DHAVE_LIBBPF)
else()
	message(STATUS "libbpf not found at configure time; building dns_monitor with runtime graceful fallback")
endif()

# Handle firewall version
if(AW_FW3)
	set(fw_source ${src_fw3})
	set(fw_libs dl ip4tc iptext iptext4 xtables)
	add_definitions(-DAW_FW3)
	message(STATUS "Building with fw3")
	set(src_fw3
		fw_iptables.c fw3_iptc.c ipset.c
	)
elseif(AW_VPP)
	set(fw_source ${src_vpp})
	add_definitions(-DAW_VPP)
	message(STATUS "Building with VPP")
	set(src_vpp
		fw_vpp.c
	)
else()
	set(fw_source ${src_fw4})
	set(fw_libs nftnl mnl)
	if(HAVE_LIBBPF)
		list(APPEND fw_libs bpf)
	endif()
	add_definitions(-DAW_FW4)
	message(STATUS "Building with fw4")
	set(src_fw4
		fw_nft.c
	)
endif()

# Build targets
add_executable(wdctlx ${src_wdctlx})

add_executable(wifidogx 
	${src_apfreewifidog}
	${fw_source}
)

target_link_libraries(wifidogx
	${common_libs}
	${fw_libs}
	${CURL_LIBRARIES}
)

target_link_libraries(wdctlx
	event
)

# Installation
install(TARGETS wifidogx wdctlx
	RUNTIME DESTINATION bin
)
