# Copyright (c) 2020-2022 Charlie Burnett <burne251@umn.edu>
# SPDX-License-Identifier: ISC OR Apache-2.0

# easier to just split this off due to complexity

include(FindPerl)

function(find_perl_module)
    set(NAME ${ARGV0})
    set(PERL_MODULE_VERSION ${ARGV1})
    cmake_parse_arguments(PERL_MODULE "REQUIRED" "RESULT" ""
            ${ARGN})
    if (NOT PERL_EXECUTABLE)
        if (PERL_MODULE_REQUIRED)
            message(FATAL_ERROR
                    "Perl executable not found. "
                    "Please set PERL_EXECUTABLE to the path of your Perl "
                    "executable.")
        else ()
            message("Perl executable not found. "
                    "Please set PERL_EXECUTABLE to the path of your Perl "
                    "executable.")
        endif ()
    endif ()
    string(REPLACE "::" "_" _Perl_mod_name ${NAME})
    if (PERL_MODULE_RESULT)
        set(OUTPUT_VAR "${PERL_MODULE_RESULT}")
    else ()
        set(OUTPUT_VAR "PERL_MODULE_${_Perl_mod_name}_FOUND")
    endif ()
    if (NOT ${OUTPUT_VAR})
        message(STATUS "Checking for Perl module ${NAME}")
        execute_process(COMMAND ${PERL_EXECUTABLE} -M${NAME} -e ""
                OUTPUT_QUIET ERROR_VARIABLE _Perl_mod_error)
        if (NOT _Perl_mod_error)
            execute_process(COMMAND
                    ${PERL_EXECUTABLE} -M${NAME} -e
                    "print $${NAME}::VERSION"
                    OUTPUT_VARIABLE _Perl_mod_version)
            message(STATUS
                    "  Found ${NAME}, version ${_Perl_mod_version}")
            set("${OUTPUT_VAR}" TRUE CACHE BOOL
                    "Perl module ${_Perl_mod_version} found")
            set(PERL_MODULE_${_Perl_mod_name}_VERSION
                    CACHE STRING "Perl module '${NAME}' version")
        else ()
            if (PERL_MODULE_REQUIRED)
                message(FATAL_ERROR "Perl module ${NAME} not found.")
            else ()
                message(STATUS "  Perl module ${NAME} not found.")
            endif ()
        endif ()
        if (PERL_MODULE_VERSION)
            if (${_Perl_mod_version} VERSION_LESS PERL_MODULE_VERSION)
                if (PERL_MODULE_REQUIRED)
                    message(FATAL_ERROR
                            "Perl module ${NAME} version "
                            "${_Perl_mod_version} is too old. Please upgrade "
                            "to version ${PERL_MODULE_VERSION} or later.")
                else ()
                    message(WARNING
                            "Perl module ${NAME} version "
                            "${_Perl_mod_version} is too old. Please upgrade "
                            "to version ${PERL_MODULE_VERSION} or later.")
                endif ()
                unset("PERL_MODULE_${_Perl_mod_name}_FOUND")
            endif ()
        endif ()
    endif ()
    mark_as_advanced("${OUTPUT_VAR}" "${_Perl_mod_name}_VERSION")
endfunction()
