cmake_minimum_required (VERSION 3.9.4)
project (fixit_tiff)
include_directories("${PROJECT_SOURCE_DIR}")
include (CheckSymbolExists)

include(CheckIPOSupported)
file( GLOB fixit_tiff_SOURCES 
  "${PROJECT_SOURCE_DIR}/*.c"
  )
#
# Make a version file containing the current version from git.
#
execute_process( COMMAND git rev-list HEAD --count OUTPUT_VARIABLE REPO_REVISION OUTPUT_STRIP_TRAILING_WHITESPACE )
execute_process( COMMAND git rev-parse --abbrev-ref HEAD OUTPUT_VARIABLE BUILD_BRANCH OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process( COMMAND git describe --tags OUTPUT_VARIABLE BUILD_TAG OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process( COMMAND git rev-parse HEAD OUTPUT_VARIABLE BUILD_REV_ID OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process( COMMAND git describe --long --tags --dirty --always OUTPUT_VARIABLE BUILD_REV_ID_SHORT OUTPUT_STRIP_TRAILING_WHITESPACE)
add_definitions(-DVERSION="${BUILD_BRANCH} ${BUILD_TAG}")
add_definitions(-DREPO_REVISION="${REPO_REVISION}")
add_definitions(-std=gnu11)
add_link_options($<$<CONFIG:RELEASE>:-s>)
check_ipo_supported(RESULT LTO_IS_SUPPORTED OUTPUT LTO_CHECK_ERROR)
if (LTO_IS_SUPPORTED)
  message(STATUS "IPO / LTO enabled")
  set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
else()
  message(STATUS "IPO / LTO unsupported: <${LTO_CHECK_ERROR}>")
endif()
if(WIN32)
  SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
  SET(BUILD_SHARED_LIBRARIES OFF)
  SET(CMAKE_EXE_LINKER_FLAGS "-static")
  add_definitions(-DPCRE_STATIC)
  add_definitions(-D_POSIX_C_SOURCE=200809L)
  # FIXME: needed for MingW only
  add_definitions(-D_GNU_SOURCE=1)
endif(WIN32)
if(STATIC)
  set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
  set(BUILD_SHARED_LIBRARIES OFF)
  set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
endif()


add_executable(fixit_tiff fixit_tiff.c ${fixit_tiff_SOURCES})
add_executable(find_potential_IFD_offsets archeological_tools/find_potential_IFD_offsets.c)
add_executable(print_ifd_at_adress archeological_tools/print_ifd_at_adress.c)
set(CMAKE_EXTRA_INCLUDE_FILES tiff.h)

IF(STATIC)
  SET(OPENSSL_USE_STATIC_LIBS=1)
  option(BUILD_SHARED_LIBS "Build using static libraries" OFF)
endif()

find_package(OpenSSL REQUIRED)
if (OpenSSL_FOUND)
  MESSAGE(STATUS "found OpenSSL")
  SET(CMAKE_REQUIRED_LIBRARIES ${OPENSSL_LIBRARIES})
  INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
else(OpenSSL_FOUND)
  MESSAGE(FATAL_ERROR "No OpenSSL library found, add $OpenSSL_INCLUDE_DIR manually")
endif()

## libtiff5
include(FindPkgConfig)
if(NOT PKG_CONFIG_FOUND)
  message(FATAL_ERROR "Could not find pkg-config - currently required for libtiff")
endif()
pkg_check_modules(LIBTIFF REQUIRED IMPORTED_TARGET GLOBAL libtiff-4)
if(LIBTIFF_FOUND)
  message(STATUS "Found libtiff package")
  include_directories(${LIBTIFF_INCLUDE_DIRS})
  link_directories(${LIBTIFF_LIBRARY_DIRS})
  if (STATIC)
    # stdc++ needed to link, because lerc-library is a c++ library
    SET(TIFF_LIBRARIES ${LIBTIFF_STATIC_LIBRARIES} -lstdc++)
  else()
    SET(TIFF_LIBRARIES ${LIBTIFF_LIBRARIES})
  endif()
  SET(CMAKE_REQUIRED_LIBRARIES ${TIFF_LIBRARIES})
else()
  message(FATAL_ERROR "Could not find tiff library package!")
endif()


if(OLD_TIFF_FIND)
find_package(TIFF REQUIRED)
if(TIFF_FOUND)
  # Confirm required API is available
  #INCLUDE(CheckFunctionExists)
  SET(CMAKE_REQUIRED_LIBRARIES ${TIFF_LIBRARIES})
  #CHECK_FUNCTION_EXISTS(TIFFOpen HAVE_TIFFOPEN)
  #IF(NOT HAVE_TIFFOPEN)
  #  SET(TIFF_FOUND) # ReSET to NOT found for TIFF library
  #  MESSAGE(FATAL_ERROR "Failed to link with libtiff - TIFFOpen function not found")
  #ENDIF()

  # CHECK_FUNCTION_EXISTS(TIFFMergeFieldInfo HAVE_TIFFMERGEFIELDINFO)
  #IF(NOT HAVE_TIFFMERGEFIELDINFO)
  #  SET(TIFF_FOUND) # ReSET to NOT found for TIFF library
  #  MESSAGE(FATAL_ERROR "Failed to link with libtiff - TIFFMergeFieldInfo function not found. libtiff 3.6.0 Beta or later required. Please upgrade or use an older version of libgeotiff")
  #ENDIF()
  INCLUDE_DIRECTORIES(${TIFF_INCLUDE_DIR})
  ADD_DEFINITIONS(-DHAVE_TIFF=1)

  CHECK_SYMBOL_EXISTS(TIFFTAG_IMAGELAYER "tiff.h" HAVE_TIFFTAG_IMAGE_LAYER)
  IF(NOT HAVE_TIFFTAG_IMAGE_LAYER)
    MESSAGE(STATUS "old tiff library detected, -DTIFFTAG_IMAGELAYER=34732 added")
    ADD_DEFINITIONS(-DTIFFTAG_IMAGELAYER=34732)
  ENDIF()

  CHECK_SYMBOL_EXISTS(TIFF_UINT64_T "tiff.h" HAVE_TIFF_UINT64_T)
  IF(NOT HAVE_TIFF_UINT64_T)
    MESSAGE(STATUS "old tiff library detected, -Duint64='unsigned long long' added")

    if(SIZEOF_UNSIGNED_LONG EQUAL 8)
      set(TIFF_UINT64_T "unsigned long")
      set(TIFF_UINT64_FORMAT "%lu")
    elseif(SIZEOF_UNSIGNED_LONG_LONG EQUAL 8)
      set(TIFF_UINT64_T "unsigned long long")
      if (MINGW)
        set(TIFF_UINT64_FORMAT "%I64u")
      else()
        set(TIFF_UINT64_FORMAT "%llu")
      endif()
    endif()
  ENDIF()

  CHECK_SYMBOL_EXISTS(TIFF_INT64_T "tiff.h" HAVE_TIFF_INT64_T)
  IF(NOT HAVE_TIFF_INT64_T)
    MESSAGE(STATUS "old tiff library detected, -Dint64='long long' added")
    if(SIZEOF_SIGNED_LONG EQUAL 8)
      set(TIFF_INT64_T "signed long")
      set(TIFF_INT64_FORMAT "%ld")
    elseif(SIZEOF_SIGNED_LONG_LONG EQUAL 8)
      set(TIFF_INT64_T "signed long long")
      if (MINGW)
        set(TIFF_INT64_FORMAT "%I64d")
      else()
        set(TIFF_INT64_FORMAT "%lld")
      endif()
    endif()

  ENDIF()

else(TIFF_FOUND)
  MESSAGE(FATAL_ERROR "No TIFF library found, add $TIFF_INCLUDE_DIR manually")
endif(TIFF_FOUND)
endif()

TARGET_LINK_LIBRARIES(fixit_tiff ${OPENSSL_LIBRARIES} ${TIFF_LIBRARIES} )
TARGET_LINK_LIBRARIES(find_potential_IFD_offsets ${TIFF_LIBRARIES})
TARGET_LINK_LIBRARIES(print_ifd_at_adress ${TIFF_LIBRARIES})

install( TARGETS fixit_tiff find_potential_IFD_offsets print_ifd_at_adress
  RUNTIME DESTINATION bin
  LIBRARY DESTINATION lib
)
install(DIRECTORY 
  ../examples
  DESTINATION share/fixit_tiff/
)

file( GLOB README_FILES "../README*" "../FAQ" "../LICENSE" "../TODO" "../BUGS")
install(FILES ${README_FILES} DESTINATION share/fixit_tiff/)
install(FILES ../doc/fixit_tiff.1 DESTINATION man/man1/)

# CPACK definitions
include(InstallRequiredSystemLibraries)

set (CPACK_PACKAGE_VENDOR "Andreas Romeyke")
string(REGEX REPLACE "^v([0-9]+).*" "\\1" MAJOR_VERSION ${BUILD_TAG})
string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*"  "\\1" MINOR_VERSION ${BUILD_TAG})
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" PATCH_VERSION ${BUILD_TAG})

message( "BUILDTAG (after) : '${BUILD_TAG}'")
message( "MAJOR VERSION: ${MAJOR_VERSION}")
message( "MINOR VERSION: ${MINOR_VERSION}")
message( "PATCH VERSION: ${PATCH_VERSION}")
set (CPACK_PACKAGE_NAME "fixit-tiff")
set (CPACK_PACKAGE_VERSION_MAJOR ${MAJOR_VERSION})
set (CPACK_PACKAGE_VERSION_MINOR ${MINOR_VERSION})
set (CPACK_PACKAGE_VERSION_PATCH ${PATCH_VERSION})
set (CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/../LICENSE")
set (CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/../README.1st")
set (CPACK_GENERATOR "TGZ;STGZ;TZ;DEB;RPM")
#set (CPACK_GENERATOR "DEB")
set (CPACK_PACKAGE_CONTACT "Andreas Romeyke fixit_tiff@andreas-romeyke.de")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "fixit_tiff is a tool to fix some issues in tiffs")
set(CPACK_PACKAGE_DESCRIPTION "fixit_tiff is a tool to repair broken TIFFs (pE. wrong tagorder, wrong datetime, clean tags)
 It works on commandline and therefore it is embedable in scripts.
 fixit_tiff can fix problems where Exiftool fails. It comes also
 with tools to scan and analyze ImageFileDirectories in TIFF files")

# Debian related
#set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc (>= 6.0)")
set(CPACK_DEBIAN_PACKAGE_SECTION "misc")
set(CPACK_DEBIAN_COMPRESSION_TYPE "xz")
set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
set (CPACK_DEBIAN_PACKAGE_VERSION ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION})
#set (CPACK_DEBIAN_PACKAGE_ARCHITECTURE amd64)
set (CPACK_DEBIAN_PACKAGE_MAINTAINER ${CPACK_PACKAGE_CONTACT})
set (CPACK_DEBIAN_PACKAGE_DESCRIPTION "${CPACK_PACKAGE_DESCRIPTION_SUMMARY}
 ${CPACK_PACKAGE_DESCRIPTION}")
set (CPACK_DEBIAN_PACKAGE_PRIORITY "optional")

include(CPack)
