#----------------------- minimum version of cmake to use ------------

cmake_minimum_required(VERSION 2.8.12...3.10)

project (OSCam C)

cmake_policy(SET CMP0003 NEW)
if(POLICY CMP0042)
  cmake_policy(SET CMP0042 NEW)
endif()
if(POLICY CMP0054)
  cmake_policy(SET CMP0054 NEW)
endif()

#----------------------- detect system ------------------------------

if (CMAKE_CROSSCOMPILING)
	if (OSCAM_SYSTEM_NAME MATCHES "Tuxbox")
		set (OSCamOperatingSystem "Tuxbox")
	elseif (OSCAM_SYSTEM_NAME MATCHES "TripleDragon")
		set (OSCamOperatingSystem "TripleDragon")
	elseif (OSCAM_SYSTEM_NAME MATCHES "Coolstream")
		set (OSCamOperatingSystem "NeutrinoHD")
	elseif (OSCAM_SYSTEM_NAME MATCHES "CST2")
		set (OSCamOperatingSystem "NHD2")
	elseif (OSCAM_SYSTEM_NAME MATCHES "NSLU2")
		set (OSCamOperatingSystem "SlugOS")
	elseif (OSCAM_SYSTEM_NAME MATCHES "WRT350NV2")
		set (OSCamOperatingSystem "OpenWRT")
		set (CS_OS_HW "wrt350nv2")
	elseif (OSCAM_SYSTEM_NAME MATCHES "Dockstar")
		set (OSCamOperatingSystem "OpenWRT")
		set (CS_OS_HW "dockstar")
	elseif (OSCAM_SYSTEM_NAME MATCHES "Fonera2")
		set (OSCamOperatingSystem "Fonera2")
	elseif (OSCAM_SYSTEM_NAME MATCHES "DIR-825")
		set (OSCamOperatingSystem "DIR-825")
	elseif (OSCAM_SYSTEM_NAME MATCHES "AZBox")
		set (OSCamOperatingSystem "AZBox")
	elseif (OSCAM_SYSTEM_NAME MATCHES "SU980")
		set (OSCamOperatingSystem "SU980")
	elseif (OSCAM_SYSTEM_NAME MATCHES "MCA")
		set (OSCamOperatingSystem "MCA")
	elseif (OSCAM_SYSTEM_NAME MATCHES "agv2+w")
		set (OSCamOperatingSystem "agv2+w")
	elseif (OSCAM_SYSTEM_NAME MATCHES "WRT54G")
		set (OSCamOperatingSystem "WRT54G")
	elseif (OSCAM_SYSTEM_NAME MATCHES "Amino")
		set (OSCamOperatingSystem "Amino")
	elseif (OSCAM_SYSTEM_NAME MATCHES "QboxHD")
		set (OSCamOperatingSystem "QboxHD")
	elseif (OSCAM_SYSTEM_NAME MATCHES "Padre")
		set (OSCamOperatingSystem "Padre")
	elseif (OSCAM_SYSTEM_NAME MATCHES "FriendlyARM")
		set (OSCamOperatingSystem "FriendlyARM")
	elseif (OSCAM_SYSTEM_NAME MATCHES "Amsmc")
		set (OSCamOperatingSystem "Amsmc")
	else (OSCAM_SYSTEM_NAME MATCHES "Tuxbox")
		message (STATUS "Unknown cross system name: <${CMAKE_SYSTEM_NAME}>")
		set (OSCamOperatingSystem "Unknown")
	endif (OSCAM_SYSTEM_NAME MATCHES "Tuxbox")
else (CMAKE_CROSSCOMPILING)
	if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
		set (OSCamOperatingSystem "Linux")
	elseif (${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
		set (OSCamOperatingSystem "FreeBSD")
	elseif (${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD")
		set (OSCamOperatingSystem "OpenBSD")
	elseif (OSCamOperatingSystem MATCHES "Padre")
		add_definitions ("-DPADRE -DSPARC")
		set (DEFAULT_CS_CONFDIR "/etc/oscam")
	elseif (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
		set (OSCamOperatingSystem "Mac OS X")
		execute_process(COMMAND sw_vers -productVersion COMMAND cut -c 1-4 COMMAND tr -d '\n' OUTPUT_VARIABLE SWVER)
		execute_process(COMMAND xcodebuild -version COMMAND grep Xcode COMMAND sed "s/Xcode\ //g" COMMAND tr -d '\n' OUTPUT_VARIABLE XCODEVER)
		message (STATUS "mac sdk version is ${SWVER}")
		message (STATUS "mac Xcode version is ${XCODEVER}")
		add_definitions ("-w")
		set (CMAKE_OSX_DEPLOYMENT_TARGET "${SWVER}")
		if (SWVER GREATER 10.5)
			set (CMAKE_OSX_ARCHITECTURES "x86_64")
		endif (SWVER GREATER 10.5)
		if (SWVER EQUAL 10.7 AND XCODEVER LESS 4.3)
			message (STATUS "Compiling with xcode less then 4.3 on 10.7 If You have time update You're Xcode")
		endif (SWVER EQUAL 10.7 AND XCODEVER LESS 4.3)
		set (STATIC_LIBUSB True)
	elseif (${CYGWIN})
		set (OSCamOperatingSystem "Windows/Cygwin")
		set (CMAKE_SYSTEM_PROCESSOR "i386")
	else (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
		message (STATUS "Unknown system name: <${CMAKE_SYSTEM_NAME}>")
		set (OSCamOperatingSystem "Unknown")
	endif (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
endif (CMAKE_CROSSCOMPILING)

#----------------------- some paths ------------------------------

set (OPTIONAL_LINK_DIR "" CACHE STRING "Some optional link directories")
set (OPTIONAL_INCLUDE_DIR "" CACHE STRING "Some optional include directories")

if (OSCamOperatingSystem MATCHES "Windows/Cygwin")
	include_directories (
		${CMAKE_CURRENT_SOURCE_DIR}/csctapi
		${CMAKE_CURRENT_SOURCE_DIR}/cscrypt
		${CMAKE_CURRENT_SOURCE_DIR}/minilzo
		${CMAKE_CURRENT_SOURCE_DIR}/extapi/cygwin
		/usr/include/w32api
		${OPTIONAL_INCLUDE_DIR}
		)
else (OSCamOperatingSystem MATCHES "Windows/Cygwin")
	include_directories (
		${CMAKE_CURRENT_SOURCE_DIR}/csctapi
		${CMAKE_CURRENT_SOURCE_DIR}/cscrypt
		${CMAKE_CURRENT_SOURCE_DIR}/minilzo
		${OPTIONAL_INCLUDE_DIR}
		)
endif (OSCamOperatingSystem MATCHES "Windows/Cygwin")

if(OSCamOperatingSystem MATCHES "Windows/Cygwin")
	link_directories (
		/usr/lib
		/usr/lib/w32api
		/cygdrive/c/WINDOWS/system32/
		${OPTIONAL_LINK_DIR}
		)
else (OSCamOperatingSystem MATCHES "Windows/Cygwin")
	link_directories (
		${OPTIONAL_LINK_DIR}
		)
endif (OSCamOperatingSystem MATCHES "Windows/Cygwin")

#----------------------- global options ------------------------------

if (OSCamOperatingSystem MATCHES "Linux")
	set (DEFAULT_CS_CONFDIR "/usr/local/etc")
elseif (OSCamOperatingSystem MATCHES "Mac OS X")
	if (NOT HAVE_PCSC EQUAL 0)
		add_definitions ("-DWITH_PCSC=1")
	endif (NOT HAVE_PCSC EQUAL 0)
	set (DEFAULT_CS_CONFDIR "/usr/local/etc")
elseif (OSCamOperatingSystem MATCHES "Tuxbox")
	set (DEFAULT_CS_CONFDIR "/var/tuxbox/config")
elseif (OSCamOperatingSystem MATCHES "TripleDragon")
	add_definitions ("-DSTB04SCI=1")
	set (DEFAULT_CS_CONFDIR "/var/tuxbox/config")
elseif (OSCamOperatingSystem MATCHES "NeutrinoHD")
	add_definitions ("-DWITH_COOLAPI=1")
	set (USE_COOLAPI "USE_COOLAPI")
	set (DEFAULT_CS_CONFDIR "/var/tuxbox/config")
elseif (OSCamOperatingSystem MATCHES "NHD2")
	add_definitions ("-DWITH_COOLAPI2=1")
	set (USE_COOLAPI2 "USE_COOLAPI2")
	set (DEFAULT_CS_CONFDIR "/var/tuxbox/config")
elseif (OSCamOperatingSystem MATCHES "SlugOS")
	set (DEFAULT_CS_CONFDIR "/var/etc")
elseif (OSCamOperatingSystem MATCHES "OpenWRT")
	if (CS_OS_HW MATCHES "wrt350nv2")
		set (DEFAULT_CS_CONFDIR "/etc/oscam")
	elseif (CS_OS_HW MATCHES "dockstar")
		set (DEFAULT_CS_CONFDIR "/usr/oscam")
	endif (CS_OS_HW MATCHES "wrt350nv2")
elseif (OSCamOperatingSystem MATCHES "Fonera2")
	set (DEFAULT_CS_CONFDIR "/var/etc")
elseif (OSCamOperatingSystem MATCHES "DIR-825")
	set (DEFAULT_CS_CONFDIR "/var/etc")
elseif (OSCamOperatingSystem MATCHES "AZBox")
	add_definitions ("-DWITH_AZBOX=1")
	set (USE_AZBOX "USE_AZBOX")
	set (DEFAULT_CS_CONFDIR "/PLUGINS/OpenXCAS/oscamCAS")
elseif (OSCamOperatingSystem MATCHES "SU980")
	set (USE_SU980 "USE_SU980")
	add_definitions ("-DWITH_SU980=1")
	set (DEFAULT_CS_CONFDIR "/var/tuxbox/config")
elseif (OSCamOperatingSystem MATCHES "MCA")
	add_definitions ("-DWITH_MCA=1")
	set (USE_MCA "USE_MCA")
	set (DEFAULT_CS_CONFDIR "/var/mca/d1")
elseif (OSCamOperatingSystem MATCHES "agv2+w")
	set (DEFAULT_CS_CONFDIR "/etc")
elseif (OSCamOperatingSystem MATCHES "WRT54G")
	set (DEFAULT_CS_CONFDIR "/jffs/etc/config/oscam")
elseif (OSCamOperatingSystem MATCHES "Amino")
	set (DEFAULT_CS_CONFDIR "/var/tuxbox/config")
elseif (OSCamOperatingSystem MATCHES "QboxHD")
	add_definitions ("-DQBOXHD=1")
	set (DEFAULT_CS_CONFDIR "/var/tuxbox/config")
elseif (OSCamOperatingSystem MATCHES "Windows/Cygwin")
	add_definitions ("-static -DWITH_PCSC=1")
	set (DEFAULT_CS_CONFDIR ".")
elseif (OSCamOperatingSystem MATCHES "FreeBSD")
	add_definitions ("-I/usr/local/include -L/usr/local/lib")
	set (DEFAULT_CS_CONFDIR ".")
elseif (OSCamOperatingSystem MATCHES "OpenBSD")
	add_definitions ("-I/usr/local/include -L/usr/local/lib")
	set (DEFAULT_CS_CONFDIR "/etc/oscam")
elseif (OSCamOperatingSystem MATCHES "FriendlyARM")
	set (DEFAULT_CS_CONFDIR ".")
elseif (OSCamOperatingSystem MATCHES "Amsmc")
	set (USE_AMSMC "USE_AMSMC")
	add_definitions ("-DWITH_AMSMC=1")
endif (OSCamOperatingSystem MATCHES "Linux")

set (CS_CONFDIR ${DEFAULT_CS_CONFDIR} CACHE STRING "Default path for the config files")
add_definitions ("-DCS_CONFDIR=\"${CS_CONFDIR}\"")

#----------------------- git submodule support ------------------------------

execute_process(
	COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --submodule
	WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
)

# upx compression
execute_process (COMMAND upx --version RESULT_VARIABLE UPX_RET ERROR_QUIET COMMAND head -n 1 OUTPUT_VARIABLE UPX_VER OUTPUT_STRIP_TRAILING_WHITESPACE)
set(COMP_LEVEL "--best" CACHE STRING "${COMP_LEVEL}")

if (NOT UPX_RET EQUAL 0)
	set (UPX_VER "n.a.")
endif (NOT UPX_RET EQUAL 0)

if (NOT USE_COMPRESS OR USE_COMPRESS EQUAL 0)
	message (STATUS "COMPRESSION is disabled")
elseif (USE_COMPRESS EQUAL 1 AND NOT UPX_RET EQUAL 0)
	set (USE_COMPRESS "0")
	message (STATUS "COMPRESSION requested but upx binary NOT FOUND  COMPILING WHITOUT UPX COMPRESSION !!!")
else (NOT USE_COMPRESS OR USE_COMPRESS EQUAL 0)
	set (USE_COMPRESS_FLAG "USE_COMPRESS")
	set (UPX_SPLIT_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/signing/upx.")
	add_definitions ("-D'USE_COMPRESS=\"${USE_COMPRESS}\"' -D'COMP_LEVEL=\"${COMP_LEVEL}\"' -D'COMP_VERSION=\"${UPX_VER}\"'")
	message (STATUS "COMPRESSION is added by You, upx compress binary after compiling")
endif (NOT USE_COMPRESS OR USE_COMPRESS EQUAL 0)

# binary signing
find_program(STAT NAMES gnustat)
find_program(STAT NAMES stat)
find_program(SPLIT NAMES gsplit)
find_program(SPLIT NAMES split)
execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --enabled WITH_SIGNING OUTPUT_VARIABLE CONFIG_WITH_SIGNING OUTPUT_STRIP_TRAILING_WHITESPACE)
if (CONFIG_WITH_SIGNING MATCHES "N" AND WITH_SIGNING EQUAL 1)
	message (STATUS "SIGNING is added by You compiling with signing included")
elseif (CONFIG_WITH_SIGNING MATCHES "Y" AND WITH_SIGNING EQUAL 1)
	message (STATUS "SIGNING is added by You but it was already enabled by config file")
elseif (CONFIG_WITH_SIGNING MATCHES "Y" AND NOT DEFINED WITH_SIGNING)
	message(STATUS "SIGNING is added by config file ${CONFIG_WITH_SIGNING} compiling with signing included")
elseif (CONFIG_WITH_SIGNING MATCHES "N" OR WITH_SIGNING EQUAL 0)
	set (WITH_SIGNING "0")
	message (STATUS "SIGNING is disabled")
endif (CONFIG_WITH_SIGNING MATCHES "N" AND WITH_SIGNING EQUAL 1)

if ((CONFIG_WITH_SIGNING MATCHES "Y" AND NOT WITH_SIGNING EQUAL 0) OR WITH_SIGNING EQUAL 1)
	execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --create-cert ecdsa prime256v1 ca ERROR_QUIET)
	execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --cert-file cert RESULT_VARIABLE CONFIG_RET ERROR_QUIET OUTPUT_VARIABLE SIGN_CERT OUTPUT_STRIP_TRAILING_WHITESPACE)
	if (NOT CONFIG_RET EQUAL 0)
		set (WITH_SIGNING "0")
		message (STATUS "SIGNING requested but certificates NOT FOUND  COMPILING WHITOUT SIGNING !!!")
	else (NOT CONFIG_RET EQUAL 0)
		add_definitions ("-DWITH_SIGNING -DWITH_SSL")
		set (WITH_SIGNING "1")
		execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --cert-file privkey ERROR_QUIET                 OUTPUT_VARIABLE SIGN_PRIVKEY OUTPUT_STRIP_TRAILING_WHITESPACE)
		execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --sign-marker                                   OUTPUT_VARIABLE SIGN_MARKER OUTPUT_STRIP_TRAILING_WHITESPACE)
		execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --upx-marker                                    OUTPUT_VARIABLE SIGN_UPXMARKER OUTPUT_STRIP_TRAILING_WHITESPACE)
		execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --cert-info COMMAND head -n 1                   OUTPUT_VARIABLE SIGN_SUBJECT OUTPUT_STRIP_TRAILING_WHITESPACE)
		execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --cert-info COMMAND tail -n 1                   OUTPUT_VARIABLE SIGN_SIGALGO OUTPUT_STRIP_TRAILING_WHITESPACE)
		execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --cert-info COMMAND head -n 4 COMMAND tail -n 1 OUTPUT_VARIABLE SIGN_VALID OUTPUT_STRIP_TRAILING_WHITESPACE)
		execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --cert-info COMMAND head -n 5 COMMAND tail -n 1 OUTPUT_VARIABLE SIGN_PUBALGO OUTPUT_STRIP_TRAILING_WHITESPACE)
		execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --cert-info COMMAND head -n 6 COMMAND tail -n 1 OUTPUT_VARIABLE SIGN_PUBBIT OUTPUT_STRIP_TRAILING_WHITESPACE)
		set (SIGN_PUBKEY "${CMAKE_CURRENT_BINARY_DIR}/signing/pkey")
		set (SIGN_HASH "${CMAKE_CURRENT_BINARY_DIR}/signing/sha256")
		set (SIGN_DIGEST "${CMAKE_CURRENT_BINARY_DIR}/signing/digest")
		string(TOUPPER ${SIGN_PUBALGO} SIGN_PUBALGO_LIST)
		string(REPLACE "-" " " SIGN_PUBALGO_LIST ${SIGN_PUBALGO_LIST})
		string(REPLACE " " "" SIGN_PUBALGO_LIST ${SIGN_PUBALGO_LIST})
		string(REPLACE ":" ";" SIGN_PUBALGO_LIST ${SIGN_PUBALGO_LIST})
		list(GET SIGN_PUBALGO_LIST 1 SIGN_PUBALGO_DEF)
		add_definitions ("-D'CERT_ALGO_${SIGN_PUBALGO_DEF}'")
	endif (NOT CONFIG_RET EQUAL 0)
elseif (CONFIG_WITH_SIGNING MATCHES "Y" AND WITH_SIGNING EQUAL 0)
	message (STATUS  " The config file has signing enabled, but You disabled it by you cmake command COMPILING WHITOUT SIGNING")
endif ((CONFIG_WITH_SIGNING MATCHES "Y" AND NOT WITH_SIGNING EQUAL 0) OR WITH_SIGNING EQUAL 1)

function(SIGN_COMMAND_OSCAM)
	file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/signing)
	add_custom_command(TARGET ${exe_name} POST_BUILD COMMAND sha256sum ${exe_name} | awk '{ print $$1 }' | tr -d '\\n' > ${SIGN_HASH}
	                                                 COMMAND openssl x509 -pubkey -noout -in ${SIGN_CERT}         -out ${SIGN_PUBKEY}
	                                                 COMMAND openssl dgst -sha256      -sign ${SIGN_PRIVKEY}      -out ${SIGN_DIGEST} ${SIGN_HASH}
	                                                 COMMAND printf '[SIGN] SHA256\('\; ${STAT} -c %s ${SIGN_HASH} | tr -d '\\n'\; printf '\): '\; cat ${SIGN_HASH}\; printf ' -> '
	                                                 COMMAND openssl dgst -sha256    -verify ${SIGN_PUBKEY} -signature ${SIGN_DIGEST} ${SIGN_HASH} | tr -d '\\n'
	                                                 COMMAND test -f ${UPX_SPLIT_PREFIX}aa && cat ${UPX_SPLIT_PREFIX}aa > ${exe_name} || true
	                                                 COMMAND printf '${SIGN_MARKER}' | cat - ${SIGN_DIGEST} >> ${exe_name}
	                                                 COMMAND test -f ${UPX_SPLIT_PREFIX}ab && cat ${UPX_SPLIT_PREFIX}ab >> ${exe_name} || true
	                                                 COMMAND printf ' <- DIGEST\('\; ${STAT} -c %s ${SIGN_DIGEST} | tr -d '\\n'\; printf '\)\\n'
	)
endfunction()
#----------------------- subdirectories ------------------------------

include (CheckIncludeFile)

check_include_file ("pthread.h" HAVE_PTHREAD)
if (HAVE_PTHREAD)
	message(STATUS "  pthread found. Adding pthread support ")
	add_definitions ("-DHAVE_PTHREAD_H")
elseif (HAVE_PTHREAD)
	message(STATUS "  no pthread found. No smartreader ")
endif (HAVE_PTHREAD)

check_include_file ("openssl/aes.h" HAVE_LIBCRYPTO)
if (HAVE_LIBCRYPTO)
	add_definitions ("-DWITH_LIBCRYPTO=1")
	set (USE_LIBCRYPTO "USE_LIBCRYPTO")
else (HAVE_LIBCRYPTO)
	message (STATUS " LIBCRYTO NOT FOUND OR DISABLED NO SSL SUPPORT POSSIBLE")
endif (HAVE_LIBCRYPTO)

execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --enabled WITH_SSL OUTPUT_VARIABLE CONFIG_WITH_SSL OUTPUT_STRIP_TRAILING_WHITESPACE)
if (CONFIG_WITH_SSL MATCHES "N" AND WITH_SSL EQUAL 1)
	message ( STATUS " ssl is added by You compiling with ssl included")
elseif (CONFIG_WITH_SSL MATCHES "Y" AND WITH_SSL EQUAL 1)
	message (STATUS " ssl is added by You but it was already enabled by config file")
elseif (CONFIG_WITH_SSL MATCHES "N" AND NOT WITH_SSL EQUAL 1)
	message (STATUS " SSL IS NOT INCLUDED IN THIS COMPILATION")
endif (CONFIG_WITH_SSL MATCHES "N" AND WITH_SSL EQUAL 1)

if (CONFIG_WITH_SSL MATCHES "Y" AND NOT WITH_SSL EQUAL 0)
	message(STATUS " ssl is added by config file ${CONFIG_WITH_SSL} compiling with ssl included")
	add_definitions ("-DWITH_SSL")
	set (WITH_SSL "1")
elseif (CONFIG_WITH_SSL MATCHES "Y" AND WITH_SSL EQUAL 0)
	message (STATUS  " The config file has ssl enabled, but You disabled it by you cmake command COMPILING WHITOUT SSL")
endif (CONFIG_WITH_SSL MATCHES "Y" AND NOT WITH_SSL EQUAL 0)

find_package(OpenSSL)
if (OPENSSL_FOUND AND HAVE_LIBCRYPTO)
	include_directories(${OPENSSL_INCLUDE_DIR})
	message(STATUS "  OpenSSL found. Using header files located at ${OPENSSL_INCLUDE_DIR}.")
	if (WITH_SSL EQUAL 1)
		set(USE_SSL "USE_SSL")
	endif (WITH_SSL EQUAL 1)
else (OPENSSL_FOUND AND HAVE_LIBCRYPTO)
	message(STATUS "SSL REQUESTED BUT OPENSSL or LYBCRYPTO NOT FOUND !!")
	if (WITH_SSL)
		message(STATUS " ssl support requested but openssl or libcrypto NOT FOUND  COMPILING WHITOUT SSL !!! ")
		set (WITH_SSL "0")
	endif (WITH_SSL)
endif (OPENSSL_FOUND AND HAVE_LIBCRYPTO)

if (NOT OSCamOperatingSystem MATCHES "Mac OS X")
	if (LIBRTDIR)
		check_include_file ("${LIBRTDIR}/include/time.h" HAVE_LIBRT_STATIC)
		if (HAVE_LIBRT_STATIC)
			if (EXISTS ${LIBRTDIR}/lib/librt.a)
				message(STATUS "  static librt found : ${LIBRTDIR}/lib/librt.a (needed by libusb).")
				add_definitions ("-I${LIBRTDIR}/include/")
				add_library(imp_librt STATIC IMPORTED)
				set_property(TARGET imp_librt PROPERTY IMPORTED_LOCATION ${LIBRTDIR}/lib/librt.a)
			else (EXISTS ${LIBRTDIR}/lib/librt.a)
				message(STATUS " ${LIBRTDIR}/lib/librt.a not found (needed by libusb). No smartreader support)")
				set (HAVE_LIBRT_STATIC False)
			endif (EXISTS ${LIBRTDIR}/lib/librt.a)
		else (HAVE_LIBRT_STATIC)
			message(STATUS "  no librt found (needed by libusb). No smartreader support")
		endif (HAVE_LIBRT_STATIC)
	else (LIBRTDIR)
		check_include_file ("time.h" HAVE_LIBRT)
		if (HAVE_LIBRT)
			message(STATUS "  librt found (needed by libusb).")
		else (HAVE_LIBRT)
			message(STATUS "  no librt found (needed by libusb. No smartreader support")
		endif (HAVE_LIBRT)
	endif (LIBRTDIR)
	if (WITH_STAPI)
		if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/stapi/liboscam_stapi.a)
			message(STATUS "  liboscam_stapi.a found")
			add_definitions ("-DWITH_STAPI=1")
			add_library(stapilib STATIC IMPORTED)
			set_property(TARGET stapilib PROPERTY IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/stapi/liboscam_stapi.a)
			set (HAVE_LIBSTAPI True)
			set (USE_STAPI "USE_STAPI")
		else (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/stapi/liboscam_stapi.a)
			message(FATAL "  liboscam_stapi.a support requested but not found! ")
			set (HAVE_LIBSTAPI False)
		endif (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/stapi/liboscam_stapi.a)
	endif (WITH_STAPI)
	if (WITH_STAPI5)
		if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/stapi/liboscam_stapi5.a)
			message(STATUS "  liboscam_stapi5.a found")
			add_definitions ("-DWITH_STAPI5=1")
			add_library(stapi5lib STATIC IMPORTED)
			set_property(TARGET stapi5lib PROPERTY IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/stapi/liboscam_stapi5.a)
			set (HAVE_LIBSTAPI5 True)
			set (USE_STAPI5 "USE_STAPI5")
		else (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/stapi/liboscam_stapi5.a)
			message(FATAL "  liboscam_stapi5.a support requested but not found! ")
			set (HAVE_LIBSTAPI5 False)
		endif (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/stapi/liboscam_stapi5.a)
	endif (WITH_STAPI5)
else (NOT OSCamOperatingSystem MATCHES "Mac OS X")
	set (HAVE_LIBRT True)
endif (NOT OSCamOperatingSystem MATCHES "Mac OS X")


if( HAVE_LIBRT OR HAVE_LIBRT_STATIC)
	if (LIBUSBDIR)
		check_include_file ("${LIBUSBDIR}/include/libusb-1.0/libusb.h" HAVE_LIBUSB)
		if (HAVE_LIBUSB AND HAVE_PTHREAD)
			if (EXISTS ${LIBUSBDIR}/lib/libusb-1.0.a)
				if (STATIC_LIBUSB EQUAL 1)
					message(STATUS "  libusb 1.0 found (${LIBUSBDIR}/lib/libusb-1.0.a). Adding smartreader support ")
					add_definitions ("-DWITH_LIBUSB=1")
					add_definitions ("-I${LIBUSBDIR}/include/")
					set (LIBUSB "USE_LIBUSB")
					add_library(imp_libusb STATIC IMPORTED)
					set_property(TARGET imp_libusb PROPERTY IMPORTED_LOCATION ${LIBUSBDIR}/lib/libusb-1.0.a)
				elseif (NOT STATIC_LIBUSB OR STATIC_LIBUSB EQUAL 0)
					set (CMAKE_FIND_ROOT_PATH ${LIBUSBDIR})
					find_library (LIBUSB_LIBRARY NAMES usb-1.0)
					message(STATUS "libusb 1.0 found (${LIBUSB_LIBRARY}). Adding smartreader support ")
					add_definitions ("-DWITH_LIBUSB=1")
					add_definitions ("-I${LIBUSBDIR}/include/")
					set (LIBUSB "USE_LIBUSB")
					add_library(imp_libusb SHARED IMPORTED)
					set_property(TARGET imp_libusb PROPERTY IMPORTED_LOCATION ${LIBUSB_LIBRARY} )
				endif (STATIC_LIBUSB EQUAL 1)
			else (EXISTS ${LIBUSBDIR}/lib/libusb-1.0.a)
					message(STATUS "  libusb 1.0 not found (${LIBUSBDIR}/lib/libusb). No smartreader support ")
					set (HAVE_LIBUSB False)
					set (HAVE_LIBRT False)
					set (HAVE_LIBRT_STATIC False)
			endif (EXISTS ${LIBUSBDIR}/lib/libusb-1.0.a)
		else (HAVE_LIBUSB AND HAVE_PTHREAD)
			message(STATUS "  no libusb 1.0 found. No smartreader support")
			set (HAVE_LIBUSB False)
			set (HAVE_LIBRT False)
			set (HAVE_LIBRT_STATIC False)
		endif (HAVE_LIBUSB AND HAVE_PTHREAD)
	else (LIBUSBDIR)
		if (NOT HAVE_LIBUSB EQUAL 0)
			check_include_file ("libusb-1.0/libusb.h" HAVE_LIBUSB)
			check_include_file ("libusb-1.0/libusb.h" PRESENT)
		endif(NOT HAVE_LIBUSB EQUAL 0)
		if (OSCamOperatingSystem MATCHES "Mac OS X")
			if (NOT HAVE_LIBUSB EQUAL 0 AND NOT PRESENT)
				find_file (USBINCL_LOC "libusb-1.0/libusb.h")
				if (EXISTS ${USBINCL_LOC})
					add_definitions ("-I/usr/local/include -L/usr/local/lib -I/usr/include -L/usr/lib")
					set (HAVE_LIBUSB True)
					set (PRESENT True)
					set (USE_LIBUSB "USE_LIBUSB")
					if (NOT STATIC_LIBUSB OR STATIC_LIBUSB EQUAL 0)
						set (STATICLIBUSB False)
					elseif (STATIC_LIBUSB EQUAL 1)
						set (STATICLIBUSB True)
					endif (NOT STATIC_LIBUSB OR STATIC_LIBUSB EQUAL 0)
				endif (EXISTS ${USBINCL_LOC})
			endif (NOT HAVE_LIBUSB EQUAL 0 AND NOT PRESENT)
		endif (OSCamOperatingSystem MATCHES "Mac OS X")
		if (NOT STATIC_LIBUSB OR STATIC_LIBUSB EQUAL 0)
			if(HAVE_LIBUSB AND HAVE_PTHREAD AND PRESENT)
				message(STATUS " libusb 1.0 found (libusb-1.0.so) Adding smartreader support ")
				add_definitions ("-DWITH_LIBUSB=1")
				set (USE_LIBUSB "USE_LIBUSB")
				set (STATICLIBUSB False)
			endif(HAVE_LIBUSB AND HAVE_PTHREAD AND PRESENT)
		elseif(STATIC_LIBUSB EQUAL 1)
			if (HAVE_LIBUSB AND HAVE_PTHREAD AND PRESENT)
				message(STATUS "  static libusb 1.0 found (libusb-1.0.a). Adding smartreader support ")
				add_definitions ("-DWITH_LIBUSB=1")
				set (USE_LIBUSB "USE_LIBUSB")
				set (STATICLIBUSB True)
			else (HAVE_LIBUSB AND HAVE_PTHREAD AND PRESENT)
				message(STATUS "  no libusb 1.0 found. No smartreader support")
				set (HAVE_LIBUSB False)
			endif (HAVE_LIBUSB AND HAVE_PTHREAD AND PRESENT)
		endif(NOT STATIC_LIBUSB OR STATIC_LIBUSB EQUAL 0)
	endif (LIBUSBDIR)
endif( HAVE_LIBRT OR HAVE_LIBRT_STATIC)

check_include_file ("PCSC/wintypes.h" HAVE_PCSC)
if (HAVE_PCSC)
	FIND_PATH (PCSC_PATH PCSC/wintypes.h)
	if(OPTIONAL_INCLUDE_DIR AND EXISTS ${OPTIONAL_INCLUDE_DIR}/PCSC/wintypes.h)
		message(STATUS "  PCSC headers found (${OPTIONAL_INCLUDE_DIR}/PCSC). Adding PCSC support ")
		add_definitions ("-DWITH_PCSC=1")
		add_definitions ("-I${OPTIONAL_INCLUDE_DIR}/PCSC")
		set (USE_PCSC "USE_PCSC")
	elseif (EXISTS ${PCSC_PATH}/PCSC/wintypes.h AND NOT OPTIONAL_INCLUDE_DIR)
		message(STATUS "  PCSC headers found (${PCSC_PATH}/PCSC). Adding PCSC support ")
		add_definitions ("-DWITH_PCSC=1")
		add_definitions ("-I${PCSC_PATH}/PCSC")
		set (USE_PCSC "USE_PCSC")
	else (OPTIONAL_INCLUDE_DIR AND EXISTS ${OPTIONAL_INCLUDE_DIR}/PCSC/wintypes.h)
		if (NOT OSCamOperatingSystem MATCHES "Mac OS X")
			set (HAVE_PCSC False)
			if(OPTIONAL_INCLUDE_DIR)
				message(STATUS "  PCSC headers not found (not in /usr/include/PCSC or /usr/local/include/PCSC or ${OPTIONAL_INCLUDE_DIR}/PCSC). No PCSC support ")
			else(OPTIONAL_INCLUDE_DIR)
				message(STATUS "  PCSC headers not found (not in /usr/include/PCSC or /usr/local/include/PCSC). No PCSC support ")
			endif(OPTIONAL_INCLUDE_DIR)
		endif (NOT OSCamOperatingSystem MATCHES "Mac OS X")
	endif(OPTIONAL_INCLUDE_DIR AND EXISTS ${OPTIONAL_INCLUDE_DIR}/PCSC/wintypes.h)
	if (OSCamOperatingSystem MATCHES "Mac OS X" AND NOT HAVE_PCSC EQUAL 0)
		set (USE_PCSC "USE_PCSC")
		set (HAVE_PCSC "1")
	endif (OSCamOperatingSystem MATCHES "Mac OS X" AND NOT HAVE_PCSC EQUAL 0)
else (HAVE_PCSC)
	if (OSCamOperatingSystem MATCHES "Windows/Cygwin")
		add_definitions ("-Icygwin")
		set (HAVE_PCSC "1")
		set (USE_PCSC "USE_PCSC")
	endif (OSCamOperatingSystem MATCHES "Windows/Cygwin")
endif (HAVE_PCSC)

execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --enabled MODULE_STREAMRELAY OUTPUT_VARIABLE CONFIG_STREAMRELAY OUTPUT_STRIP_TRAILING_WHITESPACE)
if (CONFIG_STREAMRELAY MATCHES "Y" AND NOT MODULE_STREAMRELAY EQUAL 1)
	if (LIBDVBCSADIR)
		check_include_file ("${LIBDVBCSADIR}/include/dvbcsa/dvbcsa.h" FOUND_LIBDVBCSA)
		set (LIBADVBCSA_LIBRARY "${LIBDVBCSADIR}/libdvbcsa.a")
		set (LIBDVBCSA_LIBRARY "${LIBDVBCSADIR}/libdvbcsa.so")
	else (LIBDVBCSADIR)
		check_include_file ("dvbcsa/dvbcsa.h" FOUND_LIBDVBCSA)
		set(HAVE_LIBDVBCSA ${FOUND_LIBDVBCSA})
		find_library (LIBADVBCSA_LIBRARY NAMES libdvbcsa.a)
		find_library (LIBDVBCSA_LIBRARY NAMES dvbcsa)
	endif (LIBDVBCSADIR)

	if (HAVE_LIBDVBCSA)
		if (STATIC_LIBDVBCSA AND FOUND_LIBDVBCSA AND EXISTS ${LIBADVBCSA_LIBRARY})
			message(STATUS "  static libdvbcsa found (libdvbcsa.a).")
			add_library(imp_libdvbcsa STATIC IMPORTED)
			set_property(TARGET imp_libdvbcsa PROPERTY IMPORTED_LOCATION ${LIBADVBCSA_LIBRARY})
			set (dvbcsa_link "imp_libdvbcsa")
			set (STATICLIBDVBCSA 1)
		elseif ((NOT STATIC_LIBDVBCSA OR STATIC_LIBDVBCSA EQUAL 0) AND FOUND_LIBDVBCSA AND EXISTS ${LIBDVBCSA_LIBRARY})
			message(STATUS "  libdvbcsa found (libdvbcsa.so).")
			add_library(imp_libdvbcsa SHARED IMPORTED)
			set_property(TARGET imp_libdvbcsa PROPERTY IMPORTED_LOCATION ${LIBDVBCSA_LIBRARY} )
			set(dvbcsa_link "imp_libdvbcsa")
			set (STATICLIBDVBCSA 0)
		else (STATIC_LIBDVBCSA AND FOUND_LIBDVBCSA AND EXISTS ${LIBADVBCSA_LIBRARY})
			message(FATAL_ERROR "  no libdvbcsa found!")
		endif (STATIC_LIBDVBCSA AND FOUND_LIBDVBCSA AND EXISTS ${LIBADVBCSA_LIBRARY})
		add_definitions ("-DSTATIC_LIBDVBCSA=${STATICLIBDVBCSA}")
	else (HAVE_LIBDVBCSA)
		message(FATAL_ERROR "  HAVE_LIBDVBCSA disabled!")
	endif (HAVE_LIBDVBCSA)
endif (CONFIG_STREAMRELAY MATCHES "Y" AND NOT MODULE_STREAMRELAY EQUAL 1)

# Manage config.h based on command line parameters
# Manipulate config file based on given parameters and read unset parameters

execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --enabled WITH_EMU OUTPUT_VARIABLE CONFIG_WITH_EMU OUTPUT_STRIP_TRAILING_WHITESPACE)
if (CONFIG_WITH_EMU MATCHES "Y" AND NOT WITH_EMU EQUAL 1)
	add_definitions ("-DWITH_EMU")
	set (WITH_EMU "1")
	message (STATUS "  EMU is added by config compiling with EMU")
endif (CONFIG_WITH_EMU MATCHES "Y" AND NOT WITH_EMU EQUAL 1)

if (WITH_EMU)
	execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --enabled WITH_SOFTCAM OUTPUT_VARIABLE CONFIG_WITH_SOFTCAM OUTPUT_STRIP_TRAILING_WHITESPACE)
	if (CONFIG_WITH_SOFTCAM MATCHES "Y" AND NOT WITH_SOFTCAM EQUAL 1)
		add_definitions ("-DWITH_SOFTCAM")
		set (WITH_SOFTCAM "1")
		message (STATUS "  SOFTCAM is added by config linking SoftCam.Key")
	endif (CONFIG_WITH_SOFTCAM MATCHES "Y" AND NOT WITH_SOFTCAM EQUAL 1)
endif (WITH_EMU)

execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --show-valid OUTPUT_VARIABLE config_vars_string OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REGEX MATCHALL "[A-Z0-9_]+" config_vars ${config_vars_string})

MACRO(GENERATE_OSCAM_CONFIG fullpath)
	foreach(option ${config_vars})
		if(DEFINED ${option})
			if(${option})
				execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --enable ${option})
			else(${option})
				execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --disable ${option})
			endif(${option})
		endif(DEFINED ${option})
	endforeach(option)
ENDMACRO(GENERATE_OSCAM_CONFIG fullpath)

GENERATE_OSCAM_CONFIG("${CMAKE_CURRENT_SOURCE_DIR}/config.h")

# Build config.mak and related files
# FIXME: Create USE_FLAGS and pass them to config.sh using --use-flags
execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --objdir ${CMAKE_CURRENT_BINARY_DIR} --use-flags  "${USE_STAPI} ${USE_STAPI5} /
${USE_COOLAPI} ${USE_SU980} ${USE_AZBOX} ${USE_AMSMC} ${USE_MCA} ${USE_SSL} ${USE_LIBCRYPTO} ${USE_LIBUSB} ${USE_PCSC} ${USE_COMPRESS_FLAG}" --make-config.mak)
# Generate webif/pages.c
execute_process (COMMAND make --no-print-directory --quiet -C ${CMAKE_CURRENT_SOURCE_DIR}/webif)

#----------------------- subdirectories ------------------------------

add_subdirectory (csctapi)
add_subdirectory (minilzo)
add_subdirectory (cscrypt)

#----------------------- file groups ------------------------------
execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --enabled MODULE_CAMD33 OUTPUT_VARIABLE CAMD33 OUTPUT_STRIP_TRAILING_WHITESPACE)
if (CAMD33 MATCHES "N")
set (CAMD_33 "module-camd33*")
endif (CAMD33 MATCHES "N")
if (OSCamOperatingSystem MATCHES "Mac OS X")
file (GLOB csmodules_mac  "module-dvbapi*" "module-lcd*" "${CAMD_33}")
file (GLOB csmodules_srcs "module-*.c" "webif/pages.c")
list (REMOVE_ITEM csmodules_srcs ${csmodules_mac})
file (GLOB csmodules_hdrs "module-*.h" "webif/pages.h")
list (REMOVE_ITEM csmodules_hdrs ${csmodules_mac})
file (GLOB csreaders_srcs "reader-*.c")
file (GLOB csreaders_hdrs "reader-*.h")
file (GLOB csoscam_srcs "oscam-*.c")
file (GLOB csoscam_hdrs "oscam-*.h")
file (GLOB exe_srcs "oscam.c")
file (GLOB exe_hdrs "globals.h")
file (GLOB all_srcs ${csmodules_srcs} ${csreaders_srcs} ${csoscam_srcs} ${exe_srcs})
else (OSCamOperatingSystem MATCHES "Mac OS X")
file (GLOB csmodules_srcs "module-*.c" "webif/pages.c")
file (GLOB csmodules_hdrs "module-*.h" "webif/pages.h")
file (GLOB csreaders_srcs "reader-*.c")
file (GLOB csreaders_hdrs "reader-*.h")
file (GLOB csoscam_srcs "oscam-*.c" "${CMAKE_CURRENT_BINARY_DIR}/config.c")
file (GLOB csoscam_hdrs "oscam-*.h")
file (GLOB exe_srcs "oscam.c")
file (GLOB exe_hdrs "globals.h")
file (GLOB all_srcs ${csmodules_srcs} ${csreaders_srcs} ${csoscam_srcs} ${exe_srcs})
endif (OSCamOperatingSystem MATCHES "Mac OS X")

# Add wiki pages if WEBIF_WIKI is enabled (applies to both platforms)
execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --enabled WEBIF_WIKI OUTPUT_VARIABLE CONFIG_WEBIF_WIKI OUTPUT_STRIP_TRAILING_WHITESPACE)
if (CONFIG_WEBIF_WIKI MATCHES "Y" AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/webif/pages_wiki.c")
	list (APPEND csmodules_srcs "${CMAKE_CURRENT_SOURCE_DIR}/webif/pages_wiki.c")
	message(STATUS "  WEBIF_WIKI enabled - including wiki documentation")
endif()

#----------------------- modules ------------------------------

set (csmodules "csmodules")
add_library (${csmodules} STATIC ${csmodules_srcs} ${csmodules_hdrs})

#----------------------- readers ------------------------------

set (csreaders "csreaders")
add_library (${csreaders} STATIC ${csreaders_srcs} ${csreaders_hdrs})

#----------------------- other oscam files ------------------------------

set (csoscam "csoscam")
if (NOT WITH_SIGNING)
	list(REMOVE_ITEM csoscam_srcs "${CMAKE_SOURCE_DIR}/oscam-signing.c")
	list(REMOVE_ITEM csoscam_hdrs "${CMAKE_SOURCE_DIR}/oscam-signing.h")
endif (NOT WITH_SIGNING)
add_library (${csoscam} STATIC ${csoscam_srcs} ${csoscam_hdrs})

#----------------------- the executable ------------------------------

if (NOT USE_COMPRESS EQUAL 1)
	set (exe_name "oscam")
else (NOT USE_COMPRESS EQUAL 1)
	set (exe_name "oscam-upx")
endif (NOT USE_COMPRESS EQUAL 1)
add_executable (${exe_name} ${exe_srcs} ${exe_hdrs})
target_link_libraries (${exe_name} ${csoscam} ${csmodules} ${csreaders} csctapi cscrypt minilzo)
if (WITH_SIGNING EQUAL 1)
	SIGN_COMMAND_OSCAM()
endif (WITH_SIGNING EQUAL 1)
if (USE_COMPRESS EQUAL 1)
	add_custom_command(TARGET ${exe_name} POST_BUILD COMMAND upx -q ${COMP_LEVEL} ${exe_name} | grep '^[[:space:]]*[[:digit:]]* ->' | xargs | cat | xargs -0 printf '[ UPX] %s')
	if (WITH_SIGNING EQUAL 1)
		set_property(TARGET ${exe_name} APPEND PROPERTY ADDITIONAL_CLEAN_FILES ${UPX_SPLIT_PREFIX}aa ${UPX_SPLIT_PREFIX}ab)
		add_custom_command(TARGET ${exe_name} POST_BUILD COMMAND ${SPLIT} --bytes=`grep -oba '${SIGN_UPXMARKER}' ${exe_name} | tail -1 | awk -F':' '{ print $$1 }'` ${exe_name} ${UPX_SPLIT_PREFIX})
		SIGN_COMMAND_OSCAM()
	endif (WITH_SIGNING EQUAL 1)
endif (USE_COMPRESS EQUAL 1)

if(HAVE_LIBRT AND HAVE_LIBUSB)
	if (LIBUSBDIR)
		set (libusb_link "imp_libusb")
	else(LIBUSBDIR)
		if (STATICLIBUSB)
			set (libusb_link "libusb-1.0.a")
		else (STATICLIBUSB)
			set (libusb_link "usb-1.0")
		endif(STATICLIBUSB)
	endif(LIBUSBDIR)
	if (NOT OSCamOperatingSystem MATCHES "Mac OS X")
		set (rt_link "rt")
		endif (NOT OSCamOperatingSystem MATCHES "Mac OS X")
	if (OSCamOperatingSystem MATCHES "Windows/Cygwin")
		set (setupapi_link "setupapi")
		set (ole32_link "ole32")
		set (shell32_link "shell32")
	endif (OSCamOperatingSystem MATCHES "Windows/Cygwin")
endif(HAVE_LIBRT AND HAVE_LIBUSB)

if (HAVE_LIBRT_STATIC AND HAVE_LIBUSB)
	if (LIBUSBDIR)
		set (libusb_link "imp_libusb")
	else(LIBUSBDIR)
		if (STATICLIBUSB)
			set (libusb_link "libusb-1.0.a")
		else (STATICLIBUSB)
			set (libusb_link "usb-1.0")
		endif(STATICLIBUSB)
	endif(LIBUSBDIR)
	if (NOT OSCamOperatingSystem MATCHES "Mac OS X")
		set (rt_link "imp_librt")
	endif (NOT OSCamOperatingSystem MATCHES "Mac OS X")
	if (OSCamOperatingSystem MATCHES "Windows/Cygwin")
		set (setupapi_link "setupapi")
		set (ole32_link "ole32")
		set (shell32_link "shell32")
	endif (OSCamOperatingSystem MATCHES "Windows/Cygwin")
endif (HAVE_LIBRT_STATIC AND HAVE_LIBUSB)

if (HAVE_PTHREAD)
	set (pthread_link "pthread")
endif (HAVE_PTHREAD)

if (WITH_SSL)
	target_link_libraries (${exe_name} "${OPENSSL_SSL_LIBRARIES}")
endif (WITH_SSL)

if (HAVE_LIBCRYPTO)
	target_link_libraries (${exe_name} "${OPENSSL_CRYPTO_LIBRARIES}")
endif (HAVE_LIBCRYPTO)

if (HAVE_PCSC)
if (NOT OSCamOperatingSystem MATCHES "Mac OS X")
if (NOT OSCamOperatingSystem MATCHES "Windows/Cygwin")
	target_link_libraries (${exe_name} pcsclite)
endif (NOT OSCamOperatingSystem MATCHES "Windows/Cygwin")
endif (NOT OSCamOperatingSystem MATCHES "Mac OS X")
endif (HAVE_PCSC)

if (HAVE_LIBSTAPI)
	target_link_libraries(${exe_name} stapilib)
endif (HAVE_LIBSTAPI)

if (HAVE_LIBSTAPI5)
	target_link_libraries(${exe_name} stapi5lib)
endif (HAVE_LIBSTAPI5)

add_dependencies (${exe_name} ${csoscam} ${csreaders} ${csmodules})

#----------------------- specific options ------------------------------

if (OSCamOperatingSystem MATCHES "Linux")
	set (dl_link "dl")
elseif (OSCamOperatingSystem MATCHES "Mac OS X")
	if (NOT HAVE_PCSC EQUAL 0)
		FIND_LIBRARY (PCSC_LIBRARY PCSC)
		message (STATUS "PCSC Mac OS X found : ${PCSC_LIBRARY}")
		add_definitions ("-DWITH_PCSC=1")
		target_link_libraries ( ${exe_name} ${PCSC_LIBRARY})
		set (HAVE_PCSC True)
		FIND_LIBRARY (IOKit_LIBRARY IOKit)
		target_link_libraries ( ${exe_name} ${IOKit_LIBRARY})
		FIND_LIBRARY (CoreFoundation_LIBRARY CoreFoundation)
		target_link_libraries ( ${exe_name} ${CoreFoundation_LIBRARY})
	else (NOT HAVE_PCSC EQUAL 0)
		message (STATUS "PCSC Mac OS X not found no pcsc support")
	endif (NOT HAVE_PCSC EQUAL 0)
elseif (OSCamOperatingSystem MATCHES "Tuxbox")
	set (dl_link "dl")
elseif (OSCamOperatingSystem MATCHES "TripleDragon")
	set (dl_link "dl")
elseif (OSCamOperatingSystem MATCHES "SlugOS")
elseif (OSCamOperatingSystem MATCHES "OpenWRT")
elseif (OSCamOperatingSystem MATCHES "Fonera2")
elseif (OSCamOperatingSystem MATCHES "DIR-825")
elseif (OSCamOperatingSystem MATCHES "agv2+w")
elseif (OSCamOperatingSystem MATCHES "WRT54G")
elseif (OSCamOperatingSystem MATCHES "Amino")
elseif (OSCamOperatingSystem MATCHES "QboxHD")
elseif (OSCamOperatingSystem MATCHES "Windows/Cygwin")
	message (STATUS "Windows system PCSC : winscard.dll")
	target_link_libraries (${exe_name} winscard)
	target_link_libraries (${exe_name} setupapi )
	target_link_libraries (${exe_name} ole32)
	target_link_libraries (${exe_name} shell32)
elseif (OSCamOperatingSystem MATCHES "NeutrinoHD")
	target_link_libraries (${exe_name} rt nxp)
elseif (OSCamOperatingSystem MATCHES "NHD2")
	target_link_libraries (${exe_name} lnxcssUsr lnxscsUsr lnxnotifyqUsr lnxUKAL lnxplatUsr rt)
elseif (OSCamOperatingSystem MATCHES "AZBox")
	add_library(xcas STATIC IMPORTED)
	set_property(TARGET xcas PROPERTY IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/extapi/openxcas/libOpenXCASAPI.a)
	set (xcas_link "xcas")
elseif (OSCamOperatingSystem MATCHES "SU980")
	target_link_libraries (${exe_name} rt entropic)
endif (OSCamOperatingSystem MATCHES "Linux")

target_link_libraries (${exe_name} ${libusb_link} ${rt_link} ${setupapi_link} ${ole32_link} ${shell32_link} ${pthread_link} ${dl_link} ${xcas_link} ${dvbcsa_link})

execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --oscam-version COMMAND tr -d '\n' OUTPUT_VARIABLE CS_VERSION)
add_definitions ("-D'CS_VERSION=\"${CS_VERSION}\"'")
execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --oscam-commit COMMAND tr -d '\n' OUTPUT_VARIABLE CS_GIT_COMMIT)
add_definitions ("-D'CS_GIT_COMMIT=\"${CS_GIT_COMMIT}\"'")
string(TIMESTAMP CS_BUILD_DATE "%d.%m.%Y %H:%M:%S")
add_definitions ("-D'CS_BUILD_DATE=\"${CS_BUILD_DATE}\"'")

execute_process(COMMAND ${CMAKE_C_COMPILER} -dumpmachine COMMAND tr -d '\n' OUTPUT_VARIABLE CS_TARGET)
add_definitions ("-D'CS_TARGET=\"${CS_TARGET}\"'")

execute_process (COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/config.sh --enabled WITH_ARM_NEON OUTPUT_VARIABLE CONFIG_WITH_ARM_NEON OUTPUT_STRIP_TRAILING_WHITESPACE)
if (CONFIG_WITH_ARM_NEON MATCHES "Y" AND NOT WITH_ARM_NEON EQUAL 0)
	add_definitions ("-DWITH_ARM_NEON")
	set (WITH_ARM_NEON "1")
elseif (CONFIG_WITH_ARM_NEON MATCHES "Y" AND NOT WITH_ARM_NEON EQUAL 0)
	message (STATUS  " The config file has WITH_ARM_NEON enabled, but You disabled it by you cmake command COMPILING WHITOUT arm neon optimization")
endif (CONFIG_WITH_ARM_NEON MATCHES "Y" AND NOT WITH_ARM_NEON EQUAL 0)
#----------------------- global compile and link options ------------------------------
#enable sse2 on x86, neon on arm
if (CMAKE_SYSTEM_PROCESSOR MATCHES "(x86)|(X86)|(amd64)|(AMD64)")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -msse -msse2 -msse3")
elseif (CMAKE_SYSTEM_PROCESSOR MATCHES "(arm)|(ARM)")
	if (WITH_ARM_NEON EQUAL 1)
		message(STATUS "  ARM NEON is enabled, compiling with neon optimization")
		set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mfpu=neon")
		set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -mfpu=neon")
	else (WITH_ARM_NEON EQUAL 1)
		message(STATUS "  ARM NEON is disabled, compiling without neon optimization")
	endif (WITH_ARM_NEON EQUAL 1)
endif (CMAKE_SYSTEM_PROCESSOR MATCHES "(x86)|(X86)|(amd64)|(AMD64)")

# disable warning about unused but set variables in gcc 4.6+
if (CMAKE_COMPILER_IS_GNUCC)
	execute_process(COMMAND ${CMAKE_C_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION)
	string(REGEX MATCHALL "[0-9]+" GCC_VERSION_COMPONENTS ${GCC_VERSION})
	list(GET GCC_VERSION_COMPONENTS 0 GCC_MAJOR)
	list(GET GCC_VERSION_COMPONENTS 0 GCC_MINOR)
	add_definitions ("-W -Wall ")
	set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2 -pipe -ffunction-sections -fdata-sections -fomit-frame-pointer -fno-schedule-insns")
	set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -O2")
	set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O0 -ggdb")
	set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -ggdb")
endif (CMAKE_COMPILER_IS_GNUCC)
# some optimisations
if (OSCamOperatingSystem MATCHES "Mac OS X")
	if (SWVER GREATER 10.6)
		if (SWVER EQUAL 10.7 AND XCODEVER LESS 4.3)
			add_definitions("-isysroot /Developer/SDKs/MacOSX${SWVER}.sdk")
		else (SWVER EQUAL 10.7 AND XCODEVER LESS 4.3)
			add_definitions("-isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX${SWVER}.sdk")
		endif (SWVER EQUAL 10.7 AND XCODEVER LESS 4.3)
	elseif(SWVER LESS 10.7)
		add_definitions("-isysroot /Developer/SDKs/MacOSX${SWVER}.sdk")
	endif (SWVER GREATER 10.6)
endif (OSCamOperatingSystem MATCHES "Mac OS X")

# we don't want the '-rdynamic' in the link command
set (CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")

# we want to strip if not Debug build
if (OSCamOperatingSystem MATCHES "Mac OS X")
	if (SWVER MATCHES "10.8")
		if (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
				set (CMAKE_EXE_LINKER_FLAGS "-isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX${SWVER}.sdk")
		else (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
				message (STATUS "  building with debug")
				set (CMAKE_EXE_LINKER_FLAGS "-ggdb -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX${SWVER}.sdk")
		endif (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
	elseif (SWVER MATCHES "10.7")
		if (SWVER EQUAL 10.7 AND XCODEVER LESS 4.3)
			if (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
				set (CMAKE_EXE_LINKER_FLAGS "-isysroot /Developer/SDKs/MacOSX${SWVER}.sdk")
			else (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
				message (STATUS "  building with debug")
				set (CMAKE_EXE_LINKER_FLAGS "-ggdb -isysroot /Developer/SDKs/MacOSX${SWVER}.sdk")
			endif (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
		else(SWVER EQUAL 10.7 AND XCODEVER LESS 4.3)
			if (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
				set (CMAKE_EXE_LINKER_FLAGS "-isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX${SWVER}.sdk")
			else (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
				message (STATUS "  building with debug")
				set (CMAKE_EXE_LINKER_FLAGS "-ggdb -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX${SWVER}.sdk")
			endif (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
		endif(SWVER EQUAL 10.7 AND XCODEVER LESS 4.3)
	elseif (SWVER MATCHES "10.6")
		if (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
				set (CMAKE_EXE_LINKER_FLAGS "-isysroot /Developer/SDKs/MacOSX${SWVER}.sdk")
		else (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
				message (STATUS "  building with debug")
				set (CMAKE_EXE_LINKER_FLAGS "-ggdb -isysroot /Developer/SDKs/MacOSX${SWVER}.sdk")
		endif (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
	endif (SWVER MATCHES "10.8")
else (OSCamOperatingSystem MATCHES "Mac OS X")
		if (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
				set (CMAKE_EXE_LINKER_FLAGS "-s")
		else (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
				message (STATUS "  building with debug")
				set (CMAKE_EXE_LINKER_FLAGS "-ggdb")
		endif (NOT CMAKE_BUILD_TYPE STREQUAL Debug)
endif (OSCamOperatingSystem MATCHES "Mac OS X")

if (OSCamOperatingSystem MATCHES "Windows/Cygwin")
	set (CMAKE_EXE_LINKER_FLAGS "--enable-stdcall-fixup")
endif (OSCamOperatingSystem MATCHES "Windows/Cygwin")

#----------------------- subdirectory list smargo ------------------------------

if( HAVE_LIBRT OR HAVE_LIBRT_STATIC)
	if (HAVE_LIBUSB)
		add_subdirectory (utils)
	endif (HAVE_LIBUSB)
endif( HAVE_LIBRT OR HAVE_LIBRT_STATIC)

#--------------------------------------------------------------------------------

if (NOT OSCamOperatingSystem MATCHES "Mac OS X")
if (NOT DEFINED ENV{ANDROID_NDK})
if (NOT DEFINED ENV{ANDROID_STANDALONE_TOOLCHAIN})
	if (WITH_SOFTCAM)
		if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/SoftCam.Key)
				execute_process (COMMAND cp ${CMAKE_CURRENT_SOURCE_DIR}/SoftCam.Key ${CMAKE_CURRENT_BINARY_DIR}/SoftCam.Key)
		else (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/SoftCam.Key)
				execute_process (COMMAND touch ${CMAKE_CURRENT_BINARY_DIR}/SoftCam.Key)
		endif (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/SoftCam.Key)
		set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--format=binary -Wl,SoftCam.Key -Wl,--format=default")
		if (NOT OSCamOperatingSystem MATCHES "Windows/Cygwin")
			set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,noexecstack")
		endif (NOT OSCamOperatingSystem MATCHES "Windows/Cygwin")
	endif (WITH_SOFTCAM)
endif (NOT DEFINED ENV{ANDROID_STANDALONE_TOOLCHAIN})
endif (NOT DEFINED ENV{ANDROID_NDK})
endif (NOT OSCamOperatingSystem MATCHES "Mac OS X")

#----------------------- installation -----------------------------

file (GLOB config_files "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/oscam.*")
file (GLOB doc_files "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/txt/*.txt")
file (GLOB man1_files "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/man/*.1")
file (GLOB man5_files "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/man/*.5")
file (GLOB example_files "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/example/oscam.ac"
						 "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/example/oscam.cert"
						 "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/example/oscam.conf"
						 "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/example/oscam.guess"
						 "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/example/oscam.ird"
						 "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/example/oscam.server"
						 "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/example/oscam.services"
						 "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/example/oscam.srvid"
						 "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/doc/example/oscam.user")
file (GLOB monitor_files "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/monitor/mpcs*.sh"
						 "${CMAKE_CURRENT_SOURCE_DIR}/Distribution/monitor/mpcs*.tar")

install (PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/${exe_name}${CMAKE_EXECUTABLE_SUFFIX} DESTINATION bin COMPONENT bin)
install (FILES ${config_files} DESTINATION etc COMPONENT config)
install (FILES ${doc_files} DESTINATION share/doc/oscam COMPONENT doc)
install (FILES ${man1_files} DESTINATION share/man/man1 COMPONENT doc)
install (FILES ${man5_files} DESTINATION share/man/man5 COMPONENT doc)
install (FILES ${example_files} DESTINATION share/doc/oscam/example COMPONENT doc)
install (FILES ${monitor_files} DESTINATION share/doc/oscam/monitor COMPONENT doc)

#----------------------- we can use CPack to build pacakges --------------------------

# get version from source file
string (REGEX REPLACE ".*\"\(.*\)\".*" "\\1" CS_VERSION ${CS_VERSION})
string (REGEX REPLACE "\(.*\)\\..*\\..*" "\\1" CPACK_PACKAGE_VERSION_MAJOR ${CS_VERSION})
string (REGEX REPLACE ".*\\.\(.*\)\\..*" "\\1" CPACK_PACKAGE_VERSION_MINOR ${CS_VERSION})
string (REGEX REPLACE ".*\\..*\\.\(.*\)" "\\1" CPACK_PACKAGE_VERSION_PATCH ${CS_VERSION})
set (CPACK_PACKAGE_VERSION
	 "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}")

# compute my filename
set (CPACK_PACKAGE_FILE_NAME
	 "${PROJECT_NAME}-${CPACK_PACKAGE_VERSION}-${CS_TARGET}")

# wich archive we want to generate
set (CPACK_GENERATOR "TGZ")

# what to put in the archive
set (CPACK_STRIP_FILES TRUE)
set (CPACK_COMPONENTS_ALL bin)# config doc)

# ok, we can now use CPack
include (CPack)

#----------------------- printout resume -----------------------------

message (STATUS "")
message (STATUS "  operating system: ${OSCamOperatingSystem}")
message (STATUS "  target system: ${CS_TARGET}")
message (STATUS "  revision: ${CS_VERSION}")
message (STATUS "  commit: ${CS_GIT_COMMIT}")
message (STATUS "  build date: ${CS_BUILD_DATE}")
if (USE_COMPRESS EQUAL 1)
	message (STATUS "  packer: ${UPX_VER} (compression level ${COMP_LEVEL})")
endif (USE_COMPRESS EQUAL 1)
if (WITH_SIGNING EQUAL 1)
	message (STATUS "  signing: ${SIGN_PUBALGO}, ${SIGN_PUBBIT}, ${SIGN_SIGALGO},\n\t      Valid ${SIGN_VALID}, ${SIGN_SUBJECT}")
endif (WITH_SIGNING EQUAL 1)
if (HAVE_LIBCRYPTO)
	message (STATUS "  use system libcrypto functions")
else (HAVE_LIBCRYPTO)
	message (STATUS "  use built-in crypt functions")
endif (HAVE_LIBCRYPTO)
if (HAVE_PCSC)
	message (STATUS "  use system pcsc functions")
endif (HAVE_PCSC)
if (HAVE_PTHREAD)
	message (STATUS "  use system pthread functions")
endif (HAVE_PTHREAD)
if (HAVE_LIBUSB)
	if(STATIC_LIBUSB EQUAL 1)
		message (STATUS "  You selected to enable static libusb")
	endif(STATIC_LIBUSB EQUAL 1)
	if(STATICLIBUSB AND NOT LIBUSBDIR)
		message (STATUS "  use static libusb functions")
	else(STATICLIBUSB AND NOT LIBUSBDIR)
		if (LIBUSBDIR AND STATIC_LIBUSB EQUAL 0)
			message(STATUS "  use system libusb from selected LIBUSBDIR functions")
		elseif (LIBUSBDIR AND STATIC_LIBUSB EQUAL 1)
			message(STATUS "  use static libusb from selected LIBUSBDIR functions")
		elseif(LIBUSBDIR)
			message(STATUS " use system libusb from selected LIBUSBDIR functions")
		elseif(NOT LIBUSBDIR AND NOT STATIC_LIBUSB)
			message (STATUS "  use system libusb functions")
		endif(LIBUSBDIR AND STATIC_LIBUSB EQUAL 0)
	endif(STATICLIBUSB AND NOT LIBUSBDIR)
endif (HAVE_LIBUSB)
if (HAVE_LIBDVBCSA)
	if(STATIC_LIBDVBCSA EQUAL 1)
		message (STATUS "  You selected to enable static libdvbcsa")
	endif(STATIC_LIBDVBCSA EQUAL 1)
	if(STATICLIBDVBCSA AND NOT LIBDVBCSADIR)
		message (STATUS "  use static libdvbcsa functions")
	else(STATICLIBDVBCSA AND NOT LIBDVBCSADIR)
		if (LIBDVBCSADIR AND STATIC_LIBDVBCSA EQUAL 0)
			message(STATUS "  use system libdvbcsa from selected LIBDVBCSADIR functions")
		elseif (LIBDVBCSADIR AND STATIC_LIBDVBCSA EQUAL 1)
			message(STATUS "  use static libdvbcsa from selected LIBDVBCSADIR functions")
		elseif(LIBDVBCSADIR)
			message(STATUS " use system libdvbcsa from selected LIBDVBCSADIR functions")
		elseif(NOT LIBDVBCSADIR AND NOT STATIC_LIBDVBCSA)
			message (STATUS "  use system libdvbcsa functions")
		endif(LIBDVBCSADIR AND STATIC_LIBDVBCSA EQUAL 0)
	endif(STATICLIBDVBCSA AND NOT LIBDVBCSADIR)
endif (HAVE_LIBDVBCSA)

if (WITH_EMU)
	message (STATUS "  Compile with EMU support")
	if (WITH_SOFTCAM)
		message (STATUS "  SoftCam.Key will be linked as well")
	endif (WITH_SOFTCAM)
endif (WITH_EMU)

message (STATUS "")
