include(GNUInstallDirs)

add_executable(OpenPU
  main.cpp
  main_window.cpp
)
find_library(INTL_LIBRARY intl)
target_link_libraries(OpenPU PRIVATE openpu_core openpu_warnings be tracker shared
  $<$<BOOL:${INTL_LIBRARY}>:${INTL_LIBRARY}>)
target_compile_definitions(OpenPU PRIVATE
  GETTEXT_PACKAGE="openpu"
  OPENPU_LOCALEDIR="${CMAKE_INSTALL_PREFIX}/data/locale")
# BeAPI headers trigger -Wshadow/-Wconversion noise we cannot fix.
target_compile_options(OpenPU PRIVATE -Wno-shadow -Wno-conversion)

# Application resources: signature, version, flags (Haiku rc + xres).
# The vector icon (data/icons/openpu.hvif, generated by tools/make_icons.py) is embedded as hex.
set(OPENPU_HVIF ${PROJECT_SOURCE_DIR}/data/icons/openpu.hvif)
file(READ ${OPENPU_HVIF} OPENPU_HVIF_HEX HEX)
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${OPENPU_HVIF})
configure_file(OpenPU.rdef.in ${CMAKE_CURRENT_BINARY_DIR}/OpenPU.rdef @ONLY)
find_program(HAIKU_RC rc)
find_program(HAIKU_XRES xres)
find_program(HAIKU_MIMESET mimeset)
if(HAIKU_RC AND HAIKU_XRES)
  add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/OpenPU.rsrc
    COMMAND ${HAIKU_RC} -o ${CMAKE_CURRENT_BINARY_DIR}/OpenPU.rsrc ${CMAKE_CURRENT_BINARY_DIR}/OpenPU.rdef
    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/OpenPU.rdef)
  add_custom_target(OpenPU_rsrc DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/OpenPU.rsrc)
  add_dependencies(OpenPU OpenPU_rsrc)
  # Relink (and so re-attach the resources) when only the resources change.
  set_target_properties(OpenPU PROPERTIES LINK_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/OpenPU.rsrc)
  add_custom_command(TARGET OpenPU POST_BUILD
    COMMAND ${HAIKU_XRES} -o $<TARGET_FILE:OpenPU> ${CMAKE_CURRENT_BINARY_DIR}/OpenPU.rsrc
    COMMAND ${HAIKU_MIMESET} -f $<TARGET_FILE:OpenPU>)
endif()

# Haiku package layout: the application in apps/, a link in the Deskbar's Applications menu.
install(TARGETS OpenPU RUNTIME DESTINATION apps)
if(HAIKU_RC AND HAIKU_XRES)
  # `cmake --install --strip` rewrites the ELF file and drops the appended resources (icon,
  # signature, version): attach them again to the installed copy.
  install(CODE "
    set(app \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/apps/OpenPU\")
    execute_process(COMMAND ${HAIKU_XRES} -o \"\${app}\" ${CMAKE_CURRENT_BINARY_DIR}/OpenPU.rsrc
                    COMMAND_ERROR_IS_FATAL ANY)
    execute_process(COMMAND ${HAIKU_MIMESET} -f \"\${app}\")
  ")
endif()
install(CODE "
  set(menu \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/data/deskbar/menu/Applications\")
  file(MAKE_DIRECTORY \"\${menu}\")
  file(CREATE_LINK ../../../../apps/OpenPU \"\${menu}/OpenPU\" SYMBOLIC)
")
