#
# Find package LibArchive
#

include( ExternalProject )

IF( WIN32 )
	MESSAGE( "Deflating libarchive" )
	SET( LIBARCHIVE_VER 3.3.1 )
	SET( LIBARCHIVEDIR ${CMAKE_CURRENT_BINARY_DIR}/../_packages/libarchive )

	EXTERNALPROJECT_ADD( libarchive_ext
		URL ${CMAKE_SOURCE_DIR}/3rdparty/LibArchive/libarchive-${LIBARCHIVE_VER}.tar.gz
		PREFIX libarchive
		BINARY_DIR ${LIBARCHIVEDIR}
		INSTALL_COMMAND ""
		CMAKE_ARGS
			-DCMAKE_BUILD_TYPE:String=${CMAKE_BUILD_TYPE}
			-DBUILD_TESTING:Bool=Off
 			-DENABLE_ACL:Bool=On
 			-DENABLE_CPIO:Bool=Off
 			-DENABLE_NETTLE:Bool=Off
 			-DENABLE_OPENSSL:Bool=Off
 			-DENABLE_TAR:Bool=On
 			-DENABLE_TAR_SHARED:Bool=Off
 			-DENABLE_TEST:Bool=Off
			-DENABLE_XATTR:Bool=On )

	SET( LIBARCHIVE_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/libarchive/src/libarchive_ext/libarchive )
	FILE( MAKE_DIRECTORY ${LIBARCHIVE_INCLUDE_DIRS} )
	ADD_LIBRARY( LIBARCHIVE::LIBARCHIVESTATIC STATIC IMPORTED GLOBAL )
	ADD_DEPENDENCIES( LIBARCHIVE::LIBARCHIVESTATIC libarchive_ext )
	SET_PROPERTY( TARGET LIBARCHIVE::LIBARCHIVESTATIC PROPERTY IMPORTED_LOCATION ${LIBARCHIVEDIR}/libarchive/${CMAKE_BUILD_TYPE}/archive_static.lib )
	SET_PROPERTY( TARGET LIBARCHIVE::LIBARCHIVESTATIC PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${LIBARCHIVE_INCLUDE_DIRS} )
	SET_PROPERTY( TARGET LIBARCHIVE::LIBARCHIVESTATIC PROPERTY INTERFACE_COMPILE_DEFINITIONS LIBARCHIVE_STATIC )
ELSEIF(APPLE)
  find_library(LibArchive_LIBRARY
   NAMES archive
   HINTS ENV LD_LIBRARY_PATH
   HINTS ENV DYLD_LIBRARY_PATH
   HINTS /usr/local/opt/libarchive/lib
   PATHS
   /usr/local/opt/libarchive/lib)

find_path(LibArchive_INCLUDE_DIR
  NAMES archive.h
  HINTS /usr/local/opt/libarchive/include
  PATHS
  /usr/local/opt/libarchive/include)

   FIND_PACKAGE( LibArchive 3.3.3)
   ADD_LIBRARY( LIBARCHIVE::LIBARCHIVE STATIC IMPORTED GLOBAL )
   SET_PROPERTY( TARGET LIBARCHIVE::LIBARCHIVE PROPERTY IMPORTED_LOCATION ${LibArchive_LIBRARY} )
   SET_PROPERTY( TARGET LIBARCHIVE::LIBARCHIVE PROPERTY INTERFACE_INCLUDE_DIRECTORIES "/usr/local/opt/libarchive/include" )
ELSE()
  FIND_PACKAGE( LibArchive )
  ADD_LIBRARY( LIBARCHIVE::LIBARCHIVE STATIC IMPORTED GLOBAL )
  SET_PROPERTY( TARGET LIBARCHIVE::LIBARCHIVE PROPERTY IMPORTED_LOCATION ${LibArchive_LIBRARIES} )
  SET_PROPERTY( TARGET LIBARCHIVE::LIBARCHIVE PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${LibArchive_INCLUDE_DIRS} )
ENDIF()