find_program(RUST_RUSTC rustc)
find_program(RUST_CARGO cargo)

if(RUST_RUSTC)
  execute_process(COMMAND ${RUST_RUSTC} --version --verbose OUTPUT_VARIABLE RUSTC_VERSION_OUTPUT)
  string(REPLACE "\n" ";" RUSTC_VERSION_OUTPUT "${RUSTC_VERSION_OUTPUT}")
  set(RUST_NIGHTLY OFF)
  foreach(line ${RUSTC_VERSION_OUTPUT})
    if(NOT DEFINED RUST_VERSION_STRING)
      set(RUST_VERSION_STRING ${line})
    endif()
    if(line MATCHES "^([^:]+): (.*)$")
      set(KEY ${CMAKE_MATCH_1})
      set(VALUE ${CMAKE_MATCH_2})
      if(KEY STREQUAL "release")
        set(RUST_VERSION ${VALUE})
        set(RUST_MSRV "1.85.0")
        if(RUST_VERSION MATCHES "^[0-9]+(\\.[0-9]+)?(\\.[0-9]+)?" AND RUST_VERSION VERSION_LESS RUST_MSRV)
            message(FATAL_ERROR "Unsupported Rust compiler version: ${RUST_VERSION}. Minimum supported version is ${RUST_MSRV}")
        endif()
        if(VALUE MATCHES "nightly")
          set(RUST_NIGHTLY ON)
        endif()
      elseif(KEY STREQUAL "host")
        set(RUST_TARGET_HOST ${VALUE})
      endif()
    endif()
  endforeach()
endif()

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Rust DEFAULT_MSG RUST_RUSTC RUST_CARGO)
mark_as_advanced(RUST_RUSTC RUST_CARGO)
