find_program(QMLTESTRUNNER_BIN qmltestrunner REQUIRED
    HINTS /usr/lib/qt${QT_VERSION_MAJOR}/bin)
find_program(XVFB_RUN_BIN xvfb-run REQUIRED)

# Helper function that copies the file to the binary dir in order
# to allow for relative imports and registers it with CTest.
# For the Qt6 build, it applies a regex to make imports version-less.
function(add_qml_test TST_QML_FILE)
    get_filename_component(test_name ${TST_QML_FILE} NAME_WE)
    set(src ${CMAKE_CURRENT_SOURCE_DIR}/${TST_QML_FILE})
    set(dst ${CMAKE_CURRENT_BINARY_DIR}/${TST_QML_FILE})

    set(commands COMMAND ${CMAKE_COMMAND} -E copy ${src} ${dst})
    if(ENABLE_QT6)
        # Make import version-less: "Lomiri.Test 0.1" -> "Lomiri.Test"
        list(APPEND commands COMMAND sed -E -i "s/^(import [a-zA-Z0-9.]+) [0-9]+(\\.[0-9]+)*/\\1/" ${dst})
    endif()

    add_custom_command(OUTPUT ${dst} ${commands} DEPENDS ${src} VERBATIM)
    add_custom_target(${test_name}_qml ALL DEPENDS ${dst})

    add_test(NAME ${test_name}
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
        COMMAND ${XVFB_RUN_BIN} -a -s "-screen 0 1024x768x24" ${QMLTESTRUNNER_BIN} --platform xcb -input ${dst}
    )
endfunction()

# Find all QML test files and register them
file(GLOB QML_TST_FILES CONFIGURE_DEPENDS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} tst_*.qml)
foreach(qml_file ${QML_TST_FILES})
    add_qml_test(${qml_file})
endforeach()
