## Copyright (c) 2012-2015 Aldebaran Robotics. All rights reserved.
## Use of this source code is governed by a BSD-style license that can be
## found in the COPYING file.

FIND_PROGRAM(SVNVERSION_EXECUTABLE svnversion)
MARK_AS_ADVANCED(SVNVERSION_EXECUTABLE)


MACRO(SVNVERSION dir prefix)
  IF(SVNVERSION_EXECUTABLE)
    EXECUTE_PROCESS(COMMAND ${SVNVERSION_EXECUTABLE} -n -c ${dir}
    OUTPUT_VARIABLE SVNVERSION_OUTPUT
    RESULT_VARIABLE SVNVERSION_RESULT
    ERROR_VARIABLE SVNVERSION_ERROR
    OUTPUT_STRIP_TRAILING_WHITESPACE)

    IF(NOT ${SVNVERSION_RESULT} EQUAL 0)
      MESSAGE(STATUS "svnversion ${dir} failed with output:\n${SVNVERSION_ERROR}")
    ELSE(NOT ${SVNVERSION_RESULT} EQUAL 0)
      # Calculating version
      STRING(REGEX REPLACE "[^0-9:]+" "" SVNVERSION_OUTPUT "${SVNVERSION_OUTPUT}" )
      STRING(REGEX REPLACE "^([0-9]+:)?([0-9]+)[^0-9]*$" "\\2" ${prefix}_REVISION "${SVNVERSION_OUTPUT}" )
      STRING(REGEX MATCH "^[0-9]+$" ${prefix}_REVISION "${${prefix}_REVISION}" )
      IF("x${${prefix}_REVISION}x" STREQUAL "xx" )
        SET(${prefix}_REVISION 0)
      ENDIF("x${${prefix}_REVISION}x" STREQUAL "xx" )
    ENDIF(NOT ${SVNVERSION_RESULT} EQUAL 0)
  ELSE(SVNVERSION_EXECUTABLE)
    SET(${prefix}_REVISION 0)
  ENDIF(SVNVERSION_EXECUTABLE)
ENDMACRO(SVNVERSION dir)
