# -*- cmake -*-

set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}")
set(CPACK_PACKAGE_VERSION_MAJOR "${PROJECT_VERSION_MAJOR}")
set(CPACK_PACKAGE_VERSION_MINOR "${PROJECT_VERSION_MINOR}")
set(CPACK_PACKAGE_VERSION_PATCH "${PROJECT_VERSION_PATCH}")
set(CPACK_PACKAGE_VENDOR "${PROJECT_VENDOR}")

include(CPack)

if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
  set(windows_bundle_DLLS
    "libgcc_s_sjlj-1.dll" "libgcc_s_seh-1.dll"
    "libstdc++-6.dll" "libwinpthread-1.dll"
    "mgwfltknox-1.3.dll")
  if(ENABLE_GETTEXT)
    list(APPEND windows_bundle_DLLS
      "libintl-8.dll" "iconv.dll")
  endif()
  unset(_dllfile CACHE)
  foreach(dll ${windows_bundle_DLLS})
    find_file(_dllfile "${dll}" PATHS "${FLTK_BIN_DIR}" PATH_SUFFIXES "bin")
    if(_dllfile)
      message("!! DLL \"${dll}\" from \"${_dllfile}\"")
      install(FILES "${_dllfile}" DESTINATION "bin")
    else()
      message("!! DLL \"${dll}\" not found")
    endif()
    unset(_dllfile CACHE)
  endforeach()
endif()

if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
  set(darwin_bundle_DYLIBS
    "libfltk.1.3.dylib")
  if(ENABLE_GETTEXT)
    list(APPEND darwin_bundle_DYLIBS
      "libintl.8.dylib" "libiconv.2.dylib")
  endif()
  unset(_dylibfile CACHE)
  add_custom_target(gendylibs ALL)
  foreach(dylib ${darwin_bundle_DYLIBS})
    find_library(_dylibfile "${dylib}" PATHS ${FLTK_LIBRARY_DIRS})
    if(_dylibfile)
      message("!! DYLIB \"${dylib}\" from \"${_dylibfile}\"")
      add_custom_command(TARGET gendylibs POST_BUILD
        COMMAND "${CMAKE_COMMAND}" -E copy "${_dylibfile}" "dylibs/${dylib}"
        COMMAND "${CMAKE_INSTALL_NAME_TOOL}" -id "@executable_path/../Frameworks/${dylib}" "dylibs/${dylib}")
      foreach(dylib2 ${darwin_bundle_DYLIBS})
        add_custom_command(TARGET gendylibs POST_BUILD
          COMMAND "${CMAKE_INSTALL_NAME_TOOL}" -change "/opt/local/lib/${dylib2}" "@rpath/${dylib2}" "dylibs/${dylib}")
      endforeach()
      add_custom_command(TARGET FreeMajor POST_BUILD
        COMMAND "${CMAKE_INSTALL_NAME_TOOL}" -change "/opt/local/lib/${dylib}" "@executable_path/../Frameworks/${dylib}" $<TARGET_FILE:FreeMajor>)
      install(FILES "${CMAKE_CURRENT_BINARY_DIR}/dylibs/${dylib}" DESTINATION "${PROJECT_NAME}.app/Contents/Frameworks")
   else()
      message("!! DYLIB \"${dylib}\" not found")
    endif()
    unset(_dylibfile CACHE)
  endforeach()
endif()
