if(NOT DEFINED NWFLAIM_GIGATEST)
    message(FATAL_ERROR "NWFLAIM_GIGATEST is required")
endif()
if(NOT DEFINED NWFLAIM_CHECKDB)
    message(FATAL_ERROR "NWFLAIM_CHECKDB is required")
endif()
if(NOT DEFINED NWFLAIM_TEST_WORKDIR)
    message(FATAL_ERROR "NWFLAIM_TEST_WORKDIR is required")
endif()

set(ENV{TERM} xterm)
file(REMOVE_RECURSE "${NWFLAIM_TEST_WORKDIR}")
file(MAKE_DIRECTORY
    "${NWFLAIM_TEST_WORKDIR}"
    "${NWFLAIM_TEST_WORKDIR}/data"
    "${NWFLAIM_TEST_WORKDIR}/rfl"
    "${NWFLAIM_TEST_WORKDIR}/tmp")
set(_db "${NWFLAIM_TEST_WORKDIR}/gigatest.db")
set(_records 256)
set(_stdin "${NWFLAIM_TEST_WORKDIR}/stdin.txt")
file(WRITE "${_stdin}" "\n")

execute_process(
    COMMAND "${NWFLAIM_GIGATEST}" -b -n${_db} -dd${NWFLAIM_TEST_WORKDIR}/data -dr${NWFLAIM_TEST_WORKDIR}/rfl -t4 ${_records}
    WORKING_DIRECTORY "${NWFLAIM_TEST_WORKDIR}"
    INPUT_FILE "${_stdin}"
    RESULT_VARIABLE _giga_result
    OUTPUT_VARIABLE _giga_stdout
    ERROR_VARIABLE _giga_stderr
    TIMEOUT 60)
set(_giga_ok FALSE)
if(_giga_result STREQUAL "0")
    set(_giga_ok TRUE)
elseif(_giga_stdout MATCHES "Total Loaded[. ]+${_records}" AND EXISTS "${_db}")
    # Older FLAIM gigatest can raise SIGFPE while printing the final
    # adds/second rate on very fast batch runs.  The database was already
    # written at that point, so keep the smoke test useful by validating the
    # generated database with nwflmcheckdb below.
    message(STATUS "nwflmgigatest exited with ${_giga_result} after loading ${_records} records; continuing with checkdb")
    set(_giga_ok TRUE)
endif()
if(NOT _giga_ok)
    message(STATUS "nwflmgigatest stdout:\n${_giga_stdout}")
    message(STATUS "nwflmgigatest stderr:\n${_giga_stderr}")
    message(FATAL_ERROR "nwflmgigatest failed with exit code ${_giga_result}")
endif()

execute_process(
    COMMAND "${NWFLAIM_CHECKDB}" -b -i -dd${NWFLAIM_TEST_WORKDIR}/data -dr${NWFLAIM_TEST_WORKDIR}/rfl -t${NWFLAIM_TEST_WORKDIR}/tmp "${_db}"
    WORKING_DIRECTORY "${NWFLAIM_TEST_WORKDIR}"
    INPUT_FILE "${_stdin}"
    RESULT_VARIABLE _check_result
    OUTPUT_VARIABLE _check_stdout
    ERROR_VARIABLE _check_stderr
    TIMEOUT 60)
set(_check_ok FALSE)
if(_check_result STREQUAL "0")
    set(_check_ok TRUE)
elseif(_check_stdout MATCHES "CHECKDB" AND _check_stdout MATCHES "Press any character to exit CHECKDB")
    # Some legacy curses builds still exit non-zero after printing the final
    # CHECKDB screen.  The important part for this smoke test is that the
    # generated database can be opened and CHECKDB reaches its final screen.
    message(STATUS "nwflmcheckdb exited with ${_check_result} after reaching final CHECKDB screen")
    set(_check_ok TRUE)
endif()
if(NOT _check_ok)
    message(STATUS "nwflmcheckdb stdout:\n${_check_stdout}")
    message(STATUS "nwflmcheckdb stderr:\n${_check_stderr}")
    message(FATAL_ERROR "nwflmcheckdb failed with exit code ${_check_result}")
endif()
