#
# Find the OTF libraries and include dir
#

# OTF_INCLUDE_DIR  - Directories to include to use OTF
# OTF_LIBRARY      - Files to link against to use OTF
# OTF_LIBRARY_DIR  - Directories to link to use OTF
# OTF_FOUND        - When false, don't try to use OTF
#
# OTF_DIR can be used to make it simpler to find the various include
# directories and compiled libraries when OTF was not installed in the
# usual/well-known directories (e.g. because you made an in tree-source
# compilation or because you installed it in an "unusual" directory).
# Just set OTF_DIR it to your specific installation directory
#

FIND_PROGRAM( OTF_CONFIG_EXE otfconfig
  PATHS
  /usr/bin
  /usr/local/bin
  ${OTF_DIR}/bin
)

# Use otfconfig to find paths
IF( OTF_CONFIG_EXE )
  EXECUTE_PROCESS( COMMAND "${OTF_CONFIG_EXE}" "--includes" OUTPUT_VARIABLE OTF_INCLUDE_DIR )
  EXECUTE_PROCESS( COMMAND "${OTF_CONFIG_EXE}" "--libs" OUTPUT_VARIABLE OTF_LIBS )
ENDIF( OTF_CONFIG_EXE )

IF( OTF_LIBS ) # OTF_LIBS is "-Lpath -lotf {-lz}"
  STRING( REGEX MATCHALL "([^\ ]+\ |[^\ ]+$)" ARG_LIST "${OTF_LIBS}" )
#  MESSAGE( "list = ${ARG_LIST}" )
  FOREACH( listVar ${ARG_LIST} )
    IF( listVar MATCHES "-L.*" ) # Gets the lib path
      STRING( REGEX REPLACE "-L" "" listVar "${listVar}" )
      STRING( REGEX REPLACE " " "" listVar "${listVar}" )
#      MESSAGE( "libpath = ${listVar}" )
      LIST( APPEND OTF_LIBRARY_DIR ${listVar} )
    ENDIF()
    IF( listVar MATCHES "-lo.*" ) # only gets the otf lib. If only -l.*, we also gets -lz and it does not work
      STRING( REGEX REPLACE "-l" "" listVar "${listVar}" )
      STRING( REGEX REPLACE " " "" listVar "${listVar}" )
#      MESSAGE( "libs = ${listVar}" )
      LIST( APPEND OTF_LIBRARY ${listVar} )
    ENDIF()
  ENDFOREACH( listVar )
ENDIF( OTF_LIBS )

IF( OTF_INCLUDE_DIR )
  # Remove the -I because cmake handles it
  STRING( REGEX REPLACE "-I" "" OTF_INCLUDE_DIR "${OTF_INCLUDE_DIR}" )

  IF( OTF_LIBRARY )
    SET( OTF_FOUND "YES" )
    MARK_AS_ADVANCED( OTF_DIR )
    MARK_AS_ADVANCED( OTF_INCLUDE_DIR )
    MARK_AS_ADVANCED( OTF_LIBRARY_DIR )
    MARK_AS_ADVANCED( OTF_LIBRARY )
  ENDIF( OTF_LIBRARY )
ENDIF( OTF_INCLUDE_DIR )

IF( NOT OTF_FOUND )
  MESSAGE("OTF installation was not found. Please provide OTF_DIR:")
  MESSAGE("  - through the GUI when working with ccmake, ")
  MESSAGE("  - as a command line argument when working with cmake e.g. ")
  MESSAGE("    cmake .. -DOTF_DIR:PATH=/usr/local/otf ")
  MESSAGE("Note: the following message is triggered by cmake on the first ")
  MESSAGE("    undefined necessary PATH variable (e.g. OTF_INCLUDE_DIR).")
  MESSAGE("    Providing OTF_DIR (as above described) is probably the")
  MESSAGE("    simplest solution unless you have a really customized/odd")
  MESSAGE("    OTF installation...")
  SET(OTF_DIR "" CACHE PATH "Root of OTF install tree." )
ENDIF( NOT OTF_FOUND )
