if("$ENV{ROOTFS}" STREQUAL "")
    message(FATAL_ERROR "Define the ROOTFS environment variable to point to the appropriate sysroot.")
else()
    set(SYSROOT_PATH "$ENV{ROOTFS}")
endif()

message(STATUS "Using sysroot path: ${SYSROOT_PATH}")

set(CMAKE_CROSSCOMPILING TRUE)
set(CMAKE_SYSROOT "${SYSROOT_PATH}")
set(CMAKE_FIND_ROOT_PATH "${SYSROOT_PATH}")
set(CMAKE_SYSTEM_NAME "Linux")

set(TOOLCHAIN_CC "${CMAKE_LIBRARY_ARCHITECTURE}-gcc")
set(TOOLCHAIN_CXX "${CMAKE_LIBRARY_ARCHITECTURE}-g++")
set(TOOLCHAIN_LD "${CMAKE_LIBRARY_ARCHITECTURE}-ld")
set(TOOLCHAIN_AR "${CMAKE_LIBRARY_ARCHITECTURE}-ar")
set(TOOLCHAIN_RANLIB "${CMAKE_LIBRARY_ARCHITECTURE}-ranlib")
set(TOOLCHAIN_STRIP "${CMAKE_LIBRARY_ARCHITECTURE}-strip")
set(TOOLCHAIN_NM "${CMAKE_LIBRARY_ARCHITECTURE}-nm")

set(CMAKE_C_COMPILER ${TOOLCHAIN_CC})
set(CMAKE_CXX_COMPILER ${TOOLCHAIN_CXX})

set(LIB_DIRS
    "${SYSROOT_PATH}/lib/${CMAKE_LIBRARY_ARCHITECTURE}"
    "${SYSROOT_PATH}/usr/lib/${CMAKE_LIBRARY_ARCHITECTURE}"
)

set(COMMON_FLAGS "-I${SYSROOT_PATH}/usr/include -I${SYSROOT_PATH}/usr/include/${CMAKE_LIBRARY_ARCHITECTURE}")
FOREACH(LIB ${LIB_DIRS})
    set(COMMON_FLAGS "${COMMON_FLAGS} -L${LIB} -Wl,-rpath-link,${LIB}")
ENDFOREACH()

set(CMAKE_PREFIX_PATH "${CMAKE_PREFIX_PATH};${SYSROOT_PATH}/usr/lib/${TOOLCHAIN_HOST}")
set(CMAKE_C_FLAGS "${COMMON_FLAGS}" CACHE STRING "")
set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS}" CACHE STRING "")

set(CMAKE_FIND_ROOT_PATH "${CMAKE_INSTALL_PREFIX};${CMAKE_PREFIX_PATH};${CMAKE_SYSROOT}")

set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
