# Optional libarchive read-format plugin for UC2.
#
# Enable with -DUC2_BUILD_LIBARCHIVE_PLUGIN=ON.  Because libarchive's
# read-format API is internal (archive_read_private.h, __archive_read_*),
# the plugin links against a libarchive source tree rather than the
# installed -devel package.  Pass -DLIBARCHIVE_SOURCE_DIR=<path> to a
# checkout (or extracted release tarball) of libarchive.

option(UC2_BUILD_LIBARCHIVE_PLUGIN
       "Build the libarchive read-format plugin (milestone 1: bid)" OFF)

if(NOT UC2_BUILD_LIBARCHIVE_PLUGIN)
    return()
endif()

if(NOT DEFINED LIBARCHIVE_SOURCE_DIR)
    message(WARNING
        "UC2_BUILD_LIBARCHIVE_PLUGIN=ON but LIBARCHIVE_SOURCE_DIR is "
        "not set.  Pass -DLIBARCHIVE_SOURCE_DIR=<path-to-libarchive-source>; "
        "the plugin needs libarchive's private headers (archive_read_private.h, "
        "archive_platform.h).  Skipping plugin build.")
    return()
endif()

if(NOT EXISTS "${LIBARCHIVE_SOURCE_DIR}/libarchive/archive_read_private.h")
    message(WARNING
        "LIBARCHIVE_SOURCE_DIR=${LIBARCHIVE_SOURCE_DIR} does not look like "
        "a libarchive source tree (archive_read_private.h not found).  "
        "Skipping plugin build.")
    return()
endif()

# libarchive's headers live alongside its own config.h; set up enough
# private include paths for archive_platform.h to compile against the
# build host's <archive.h>.
add_library(uc2_libarchive STATIC archive_read_support_format_uc2.c)
target_include_directories(uc2_libarchive PRIVATE
    "${LIBARCHIVE_SOURCE_DIR}/libarchive"
)
target_link_libraries(uc2_libarchive PRIVATE uc2)
target_compile_features(uc2_libarchive PRIVATE c_std_99)

# archive_platform.h pulls in build-time configuration that is normally
# generated by libarchive's own configure.  Bypass that path: tell the
# compiler we are not using HAVE_CONFIG_H, and provide enough feature
# guesses to keep the platform header satisfied.
target_compile_definitions(uc2_libarchive PRIVATE
    PLATFORM_CONFIG_H="archive_platform_config.uc2.h"
)
configure_file(archive_platform_config.uc2.h.in
               "${CMAKE_CURRENT_BINARY_DIR}/archive_platform_config.uc2.h"
               COPYONLY)
target_include_directories(uc2_libarchive PRIVATE
    "${CMAKE_CURRENT_BINARY_DIR}"
)

message(STATUS "UC2: libarchive plugin enabled "
               "(milestone 1, source=${LIBARCHIVE_SOURCE_DIR})")
