if (CARGO)
    execute_process(COMMAND "${CARGO}" "auditable" "--help"
        RESULT_VARIABLE cargo_auditable_ret
        OUTPUT_QUIET
        ERROR_QUIET
    )
    if (${cargo_auditable_ret} EQUAL 0)
        set(audit_flags "auditable")
        message("Cargo auditable found, audit information will be added")
    else()
        set(audit_flags "")
        message("Cargo auditable not found, audit information will not be added")
    endif()

    if (("${CMAKE_BUILD_TYPE}" STREQUAL "") OR ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug"))
        set(ext_flags "")
        set(rst_build_type "debug")
    else()
        set(ext_flags "--release")
        set(rst_build_type "release")
    endif()
    message("CMAKE_BUILD_TYPE = ${CMAKE_BUILD_TYPE}")
    message("External flags = '${ext_flags}'")

    file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/target")
    function(rust_lib name)
    endfunction()

    function(rust_app name)
        add_custom_target(
                ${name} ALL
                COMMAND ${CARGO} ${audit_flags} build ${ext_flags} -p ${name} --target-dir "${CMAKE_CURRENT_BINARY_DIR}/target"
                BYPRODUCTS "${CMAKE_CURRENT_BINARY_DIR}/target/"
                WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
        )

        add_custom_command(TARGET ${name} POST_BUILD
            COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_BINARY_DIR}/target/${rst_build_type}/${name}" "${CMAKE_CURRENT_BINARY_DIR}"
            BYPRODUCTS "${CMAKE_CURRENT_BINARY_DIR}/${name}"
        )

        install(PROGRAMS "${CMAKE_CURRENT_BINARY_DIR}/${name}"
                TYPE BIN)
    endfunction()

    function(rust_unit_tests name)
        add_test(NAME "test_${name}_unit_tests"
            COMMAND ${CARGO} test ${ext_flags} -p ${name} --target-dir "${CMAKE_CURRENT_BINARY_DIR}/target/"
            WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
        )
    endfunction()

    rust_lib(cds_shmem_rs)
    #add_dependencies(cds_shmem_rs cds-shmem)

    rust_lib(util_rs)

    rust_lib(advligorts_rs)
    rust_unit_tests(advligorts_rs)

    rust_lib(ini_parsing_rs)
    rust_unit_tests(ini_parsing_rs)

    rust_lib(ligo_crc_rs)

    rust_lib(simple_pv_rs)
    rust_unit_tests(simple_pv_rs)
    # add_dependencies(simple_pv_rs_unit_tests pv::simple_pv)

    rust_app(local_dc_rs)
    rust_unit_tests(local_dc_rs)
    add_dependencies(local_dc_rs driver::shmem driver::ini_parsing util_lib)

    integration_test(
        NAME test_local_dc_rs
        SCRIPT "tests/test_local_dc_rs.py"
    )

    integration_test(
            NAME test_local_dc_rs_auto_configure
            SCRIPT "tests/test_local_dc_rs_auto_configure.py"
    )
else(CARGO)
    message("cargo not found, not building rust code")
endif(CARGO)
