cmake_minimum_required(VERSION 3.10.0 FATAL_ERROR)
project(libmaxminddb LANGUAGES C)

OPTION(BUILD_STATIC "Build static library" ON)
OPTION(BUILD_SHARED "Build shared library" ON)

if (IOS)
	set(BUILD_SHARED OFF)
endif (IOS)

message(STATUS "Looking for PACKAGE_VERSION")
file(STRINGS "${CMAKE_SOURCE_DIR}/configure" lines)
string(REGEX MATCH "PACKAGE_VERSION='[0-9.]+'" line ${lines})
if (line)
  string(REGEX REPLACE "^PACKAGE_VERSION='([0-9.]+)'$" "\\1" PACKAGE_VERSION ${line})
	add_definitions("-DPACKAGE_VERSION=\"${PACKAGE_VERSION}\"")
	message(STATUS "Looking for PACKAGE_VERSION - found ${PACKAGE_VERSION}")
else (line)
  message(FATAL_ERROR "Looking for PACKAGE_VERSION - failed")
endif (line)

set(ORIG_CONF_IN "${CMAKE_SOURCE_DIR}/include/maxminddb_config.h.in")
set(CM_CONF_IN "${CMAKE_BINARY_DIR}/include/maxminddb_config.h.in")
set(CM_CONF_H "${CMAKE_BINARY_DIR}/include/maxminddb_config.h")
include(CheckTypeSize)
check_type_size("unsigned __int128" UINT128_EXISTS)
if (UINT128_EXISTS)
  set(MMDB_UINT128_IS_BYTE_ARRAY 0)
else (UINT128_EXISTS)
  set(MMDB_UINT128_IS_BYTE_ARRAY 1)
endif (UINT128_EXISTS)
file(WRITE "${CM_CONF_IN}" "")
file(STRINGS "${ORIG_CONF_IN}" lines)
foreach (line ${lines})
  string(REGEX REPLACE "^#undef" "#cmakedefine01" l "${line}")
  file(APPEND "${CM_CONF_IN}" "${l}\n")
endforeach (line)

message(STATUS "Generating maxminddb_config.h")
configure_file(${CM_CONF_IN} ${CM_CONF_H} @ONLY)
message(STATUS "Generating maxminddb_config.h - done")

include_directories("${CMAKE_SOURCE_DIR}/include" "${CMAKE_BINARY_DIR}/include")
install(FILES  "${CMAKE_SOURCE_DIR}/include/maxminddb.h" "${CM_CONF_H}" DESTINATION include)
file(GLOB_RECURSE SRCS src/*.c)

if (BUILD_STATIC)
	add_library(maxminddb_static STATIC ${SRCS})
	set_target_properties(maxminddb_static PROPERTIES OUTPUT_NAME maxminddb)
	install(TARGETS maxminddb_static ARCHIVE DESTINATION lib)
endif (BUILD_STATIC)

if (BUILD_SHARED)
	add_library(maxminddb_shared SHARED ${SRCS})
	set_target_properties(maxminddb_shared PROPERTIES OUTPUT_NAME maxminddb)
	set_target_properties(maxminddb_shared PROPERTIES VERSION ${PACKAGE_VERSION})
	install(TARGETS maxminddb_shared LIBRARY DESTINATION lib)
endif (BUILD_SHARED)
