IF(NOT CMAKE_Go_COMPILER)
  IF(NOT $ENV{GO_COMPILER} STREQUAL "")
    GET_FILENAME_COMPONENT(CMAKE_Go_COMPILER_INIT $ENV{GO_COMPILER} PROGRAM PROGRAM_ARGS CMAKE_Go_FLAGS_ENV_INIT)

    IF(CMAKE_Go_FLAGS_ENV_INIT)
      SET(CMAKE_Go_COMPILER_ARG1 "${CMAKE_Go_FLAGS_ENV_INIT}" CACHE STRING "First argument to Go compiler")
    ENDIF()

    IF(NOT EXISTS ${CMAKE_Go_COMPILER_INIT})
      MESSAGE(SEND_ERROR "Could not find compiler set in environment variable GO_COMPILER:\n$ENV{GO_COMPILER}.")
    ENDIF()
  ENDIF()

  SET(Go_BIN_PATH
    $ENV{GOPATH}
    $ENV{GOROOT}
    $ENV{GOROOT}/../bin
    $ENV{GO_COMPILER}
    /usr/bin
    /usr/local/bin
    )

  IF(CMAKE_Go_COMPILER_INIT)
    SET(CMAKE_Go_COMPILER ${CMAKE_Go_COMPILER_INIT} CACHE PATH "Go Compiler")
  ELSE()
    FIND_PROGRAM(CMAKE_Go_COMPILER
      NAMES go
      PATHS ${Go_BIN_PATH}
    )
    EXECUTE_PROCESS(COMMAND ${CMAKE_Go_COMPILER} version OUTPUT_VARIABLE GOLANG_VERSION)
    STRING(REGEX MATCH "go[0-9]+.[0-9]+.[0-9]+[ /A-Za-z0-9]*" GOLANG_VERSION "${GOLANG_VERSION}")
    MESSAGE("-- The Golang compiler identification is ${GOLANG_VERSION}")
    MESSAGE("-- Check for working Golang compiler: ${CMAKE_Go_COMPILER}")
  ENDIF()
ENDIF()

MARK_AS_ADVANCED(CMAKE_Go_COMPILER)

CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/cmake/CMakeGoCompiler.cmake.in
  ${CMAKE_PLATFORM_INFO_DIR}/CMakeGoCompiler.cmake @ONLY)

SET(CMAKE_Go_COMPILER_ENV_VAR "GO_COMPILER")
