# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
find_path(ID3LIB_INCLUDES id3/tag.h)
find_library(ID3LIB_LIBRARY NAMES id3 id3lib)
if(ID3LIB_INCLUDES AND ID3LIB_LIBRARY)
  message(STATUS "id3lib found: ${ID3LIB_LIBRARY}")
  set(HAVE_ID3LIB 1)
  set(ID3LIB_INTERFACE_LIBRARIES ${ZLIB_LIBRARIES})
  if(NOT MSVC)
    set(ID3LIB_INTERFACE_LIBRARIES ${ID3LIB_INTERFACE_LIBRARIES} -lstdc++)
  endif()
  if(WIN32)
    set(ID3LIB_DEFINITIONS -DID3LIB_LINKOPTION=1)
    if(NOT CMAKE_CROSSCOMPILING)
      set(ID3LIB_INTERFACE_LIBRARIES ${ID3LIB_INTERFACE_LIBRARIES} -liconv)
      # libiconv-2.dll is at the same place where the compiler is, C:\msys64\mingw32\bin
      get_filename_component(_mingw_bin_dir ${CMAKE_C_COMPILER} DIRECTORY)
      install(FILES "${_mingw_bin_dir}/libiconv-2.dll"
              DESTINATION ${WITH_BINDIR} OPTIONAL)
    endif()
  elseif(APPLE)
    set(ID3LIB_INTERFACE_LIBRARIES ${ID3LIB_INTERFACE_LIBRARIES} -liconv)
  endif()
  set(ID3LIB_LIBRARIES ${ID3LIB_LIBRARY} ${ID3LIB_INTERFACE_LIBRARIES})
  set(_CMAKE_REQUIRED_LIBRARIES_TMP ${CMAKE_REQUIRED_LIBRARIES})
  set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} ${ID3LIB_LIBRARIES})
  set(_CMAKE_REQUIRED_INCLUDES_TMP ${CMAKE_REQUIRED_INCLUDES})
  set(CMAKE_REQUIRED_INCLUDES ${CMAKE_REQUIRED_INCLUDES} ${ID3LIB_INCLUDES})
  set(_CMAKE_REQUIRED_DEFINITIONS_TMP ${CMAKE_REQUIRED_DEFINITIONS})
  set(CMAKE_REQUIRED_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS} ${ID3LIB_DEFINITIONS})
  CHECK_CXX_SOURCE_COMPILES("#include <id3/globals.h>\nint main() {\n  Mp3_Headerinfo info;\n  info.vbr_bitrate = 0;\n  return 0;\n}\n" ID3LIB_VBR_SUPPORT_FOUND)
  set(CMAKE_REQUIRED_LIBRARIES ${_CMAKE_REQUIRED_LIBRARIES_TMP})
  set(CMAKE_REQUIRED_INCLUDES ${_CMAKE_REQUIRED_INCLUDES_TMP})
  set(CMAKE_REQUIRED_DEFINITIONS ${_CMAKE_REQUIRED_DEFINITIONS_TMP})

  if(NOT ID3LIB_VBR_SUPPORT_FOUND)
    set(HAVE_NO_ID3LIB_VBR 1)
  endif()

  add_library(Id3lib::Id3lib UNKNOWN IMPORTED)
  string(REPLACE "-D" "" ID3LIB_COMPILE_DEFINITIONS "${ID3LIB_DEFINITIONS}")
  set_target_properties(Id3lib::Id3lib PROPERTIES
    IMPORTED_CONFIGURATIONS RELEASE
    IMPORTED_LOCATION "${ID3LIB_LIBRARY}"
    INTERFACE_COMPILE_DEFINITIONS "${ID3LIB_COMPILE_DEFINITIONS}"
    INTERFACE_INCLUDE_DIRECTORIES "${ID3LIB_INCLUDES}"
    INTERFACE_LINK_LIBRARIES "${ID3LIB_INTERFACE_LIBRARIES}"
  )
else()
  message(FATAL_ERROR "Could not find id3lib")
endif()
