cmake_minimum_required(VERSION 3.20)
project(nxnauty CXX)

set(CMAKE_POSITION_INDEPENDENT_CODE ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(pybind11 REQUIRED)
find_package(Boost REQUIRED)   # Boost.Graph, for the shared grouping header (attr_grouping.hpp)

# --- vendored nauty -----------------------------------------------------------------------
#
# The objects are built by nauty's own makefile rather than compiled here, for two reasons:
# nauty.h (and nautil.h/gtools.h) are *generated* by nauty's configure (makefile.in:37), and
# --enable-tls is what puts `#define USE_TLS` into the generated nauty.h, which is what makes
# nauty's statics thread_local (§6).
#
# nautinv.o is needed on top of the five objects pynauty links, because nauty's own digraph
# defaults use adjacencies(), which lives in nautinv.c (R4).  pynauty gets away without it by
# keeping the graph defaults and only flipping digraph=TRUE.
set(NAUTY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/nauty2_8_8)
set(NAUTY_SOURCES nauty.c nautil.c naugraph.c schreier.c naurng.c nautinv.c)
set(NAUTY_TARGETS "")
set(NAUTY_OBJECTS "")
foreach(_source IN LISTS NAUTY_SOURCES)
  string(REPLACE ".c" ".o" _object ${_source})
  list(APPEND NAUTY_TARGETS ${_object})
  list(APPEND NAUTY_OBJECTS ${NAUTY_DIR}/${_object})
endforeach()

string(REPLACE ";" " " NAUTY_TARGETS_JOINED "${NAUTY_TARGETS}")

add_custom_command(
  OUTPUT ${NAUTY_OBJECTS}
  COMMAND ${CMAKE_COMMAND} -E chdir ${NAUTY_DIR} sh -c
          "./configure --enable-tls CFLAGS='-O4 -fPIC' && make ${NAUTY_TARGETS_JOINED}"
  DEPENDS ${NAUTY_DIR}/configure ${NAUTY_DIR}/makefile.in
          ${NAUTY_DIR}/nauty.c ${NAUTY_DIR}/nautil.c ${NAUTY_DIR}/naugraph.c
          ${NAUTY_DIR}/schreier.c ${NAUTY_DIR}/naurng.c ${NAUTY_DIR}/nautinv.c
  COMMENT "nauty: ./configure --enable-tls, then ${NAUTY_TARGETS_JOINED}"
  VERBATIM)

add_custom_target(nauty_objects DEPENDS ${NAUTY_OBJECTS})

# --- the extension ------------------------------------------------------------------------

pybind11_add_module(core
  src/nxnauty/bindings.cpp
  src/nxnauty/convert.cpp
  src/nxnauty/canon.cpp
  src/nxnauty/encode.cpp
  ${NAUTY_OBJECTS})

add_dependencies(core nauty_objects)

target_include_directories(core PRIVATE ${NAUTY_DIR} src/nxnauty src/common)

target_link_libraries(core PRIVATE Boost::headers)
