aboutsummaryrefslogtreecommitdiffstats
path: root/CMakeLists.txt
blob: 3416702c8ad17666c57029dbadd730f86572115c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
#
# Rspamd - rapid antispam system
#
# Cmake configuration file
#

############################# INITIAL SECTION #############################################
CMAKE_MINIMUM_REQUIRED(VERSION 3.1 FATAL_ERROR)

SET(RSPAMD_VERSION_MAJOR 2)
SET(RSPAMD_VERSION_MINOR 1)

# Keep two digits all the time
SET(RSPAMD_VERSION_MAJOR_NUM ${RSPAMD_VERSION_MAJOR}0)
SET(RSPAMD_VERSION_MINOR_NUM ${RSPAMD_VERSION_MINOR}0)

IF(GIT_ID)
	SET(GIT_VERSION 1)
	SET(RSPAMD_ID "${GIT_ID}")
ENDIF()

SET(RSPAMD_VERSION         "${RSPAMD_VERSION_MAJOR}.${RSPAMD_VERSION_MINOR}")

PROJECT(rspamd VERSION "${RSPAMD_VERSION}" LANGUAGES C ASM)

# This is supported merely with cmake 3.1
SET(CMAKE_C_STANDARD 11)
SET(CMAKE_C_STANDARD_REQUIRED ON)

SET(RSPAMD_MASTER_SITE_URL "https://rspamd.com")

IF(NOT RSPAMD_USER)
	SET(RSPAMD_USER "nobody")
	SET(RSPAMD_GROUP "nobody")
ENDIF(NOT RSPAMD_USER)

# Default for SysV Init
SET(RSPAMD_WORKER_NORMAL "*:11333")
SET(RSPAMD_WORKER_CONTROLLER "*:11334")
SET_PROPERTY(GLOBAL PROPERTY ALLOW_DUPLICATE_CUSTOM_TARGETS 1)

############################# OPTIONS SECTION #############################################

OPTION(ENABLE_OPTIMIZATION "Enable extra optimizations [default: OFF]"          OFF)
OPTION(SKIP_RELINK_RPATH   "Skip relinking and full RPATH for the install tree" OFF)
OPTION(ENABLE_GPERF_TOOLS  "Enable google perftools [default: OFF]"             OFF)
OPTION(ENABLE_STATIC       "Enable static compiling [default: OFF]"             OFF)
OPTION(ENABLE_LUAJIT       "Link with libluajit [default: ON]"                  ON)
OPTION(ENABLE_URL_INCLUDE  "Enable urls in ucl includes (requires libcurl or libfetch) [default: OFF]" OFF)
OPTION(NO_SHARED           "Build internal libs static [default: ON]"          ON)
OPTION(INSTALL_WEBUI       "Install web interface [default: ON]"                ON)
OPTION(WANT_SYSTEMD_UNITS  "Install systemd unit files on Linux [default: OFF]" OFF)
OPTION(ENABLE_SNOWBALL     "Enable snowball stemmer [default: ON]"              ON)
OPTION(ENABLE_CLANG_PLUGIN "Enable clang static analysing plugin [default: OFF]" OFF)
OPTION(ENABLE_HYPERSCAN    "Enable hyperscan for fast regexp processing [default: OFF]" OFF)
OPTION(ENABLE_PCRE2        "Enable pcre2 instead of pcre  [default: OFF]"         OFF)
OPTION(ENABLE_JEMALLOC     "Build rspamd with jemalloc allocator  [default: OFF]" OFF)
OPTION(ENABLE_COVERAGE     "Build rspamd with code coverage options [default: OFF]" OFF)
OPTION(ENABLE_FULL_DEBUG   "Build rspamd with all possible debug [default: OFF]" OFF)
OPTION(ENABLE_UTILS        "Build rspamd internal utils [default: OFF]" OFF)
OPTION(ENABLE_LIBUNWIND    "Use libunwind to print crash traces [default: OFF]" OFF)
OPTION(ENABLE_LUA_TRACE    "Trace all Lua C API invocations [default: OFF]" OFF)
OPTION(ENABLE_LUA_REPL     "Enables Lua repl (requires C++11 compiler) [default: ON]" ON)

INCLUDE(FindArch.cmake)
TARGET_ARCHITECTURE(ARCH)

INCLUDE(FindRagel.cmake)
IF(NOT RAGEL_FOUND)
	MESSAGE(FATAL_ERROR "Ragel is required to build rspamd")
ENDIF()

IF (NOT "${ARCH}" STREQUAL "x86_64")
	MESSAGE(STATUS "Hyperscan support is possible only for x86_64 architecture")
	SET(ENABLE_HYPERSCAN "OFF")
ENDIF()

IF ("${ARCH}" STREQUAL "x86_64")
	MESSAGE(STATUS "Enable sse2 on x86_64 architecture")
	IF((CMAKE_C_COMPILER_ID MATCHES "GNU") OR (CMAKE_C_COMPILER_ID MATCHES "Clang"))
		ADD_COMPILE_OPTIONS(-msse2)
	ELSEIF(CMAKE_C_COMPILER_ID MATCHES "Intel")
		ADD_COMPILE_OPTIONS(/QxSSE2)
	ELSEIF((CMAKE_C_COMPILER_ID MATCHES "MSVC"))
		ADD_COMPILE_OPTIONS(/arch:SSE2)
	ENDIF()
ENDIF()

IF(ENABLE_PCRE2 MATCHES "ON")
	SET(WITH_PCRE2 1)
	# For utf8 API
	LIST(APPEND CMAKE_REQUIRED_DEFINITIONS "-DPCRE2_CODE_UNIT_WIDTH=8")
ENDIF()
# Build optimized code for following CPU (default i386)
#SET(CPU_TUNE               "i686")

# Now CMAKE_INSTALL_PREFIX is a base prefix for everything
# CONFDIR - for configuration
# LOCAL_CONFDIR - for local configuration
# MANDIR - for manual pages
# RUNDIR - for runtime files
# DBDIR - for static files
# LOGDIR - for log files
# EXAMPLESDIR - for examples files

IF(NOT CONFDIR)
	SET(CONFDIR "${CMAKE_INSTALL_PREFIX}/etc/rspamd")
ENDIF(NOT CONFDIR)

IF(NOT LOCAL_CONFDIR)
	SET(LOCAL_CONFDIR "${CONFDIR}")
ENDIF(NOT LOCAL_CONFDIR)

IF(NOT MANDIR)
	SET(MANDIR "${CMAKE_INSTALL_PREFIX}/share/man")
ENDIF(NOT MANDIR)

IF(NOT RUNDIR)
	SET(RUNDIR "/var/run/rspamd")
ENDIF(NOT RUNDIR)

IF(NOT DBDIR)
	SET(DBDIR "/var/lib/rspamd")
ENDIF(NOT DBDIR)

IF(NOT LOGDIR)
	SET(LOGDIR "/var/log/rspamd")
ENDIF(NOT LOGDIR)

IF(NOT SHAREDIR)
	SET(SHAREDIR "${CMAKE_INSTALL_PREFIX}/share/rspamd")
ENDIF(NOT SHAREDIR)

IF(NOT EXAMPLESDIR)
	SET(EXAMPLESDIR "${CMAKE_INSTALL_PREFIX}/share/examples/rspamd")
ENDIF(NOT EXAMPLESDIR)

IF(NOT LUALIBDIR)
	SET(LUALIBDIR "${SHAREDIR}/lualib")
ENDIF(NOT LUALIBDIR)

IF(NOT PLUGINSDIR)
	SET(PLUGINSDIR "${SHAREDIR}/plugins")
ENDIF(NOT PLUGINSDIR)

IF(NOT RULESDIR)
	SET(RULESDIR "${SHAREDIR}/rules")
ENDIF(NOT RULESDIR)

IF(NOT WWWDIR)
	SET(WWWDIR "${SHAREDIR}/www")
ENDIF(NOT WWWDIR)

# Set libdir
IF(NOT LIBDIR)
	SET(RSPAMD_LIBDIR "${CMAKE_INSTALL_PREFIX}/lib/rspamd")
ELSE(NOT LIBDIR)
	SET(RSPAMD_LIBDIR "${LIBDIR}")
ENDIF(NOT LIBDIR)
SET(CMAKE_MACOSX_RPATH ON)
SET(CMAKE_INSTALL_RPATH "${RSPAMD_LIBDIR}")

# Set includedir
IF(NOT INCLUDEDIR)
	SET(INCLUDEDIR include/rspamd)
ENDIF(NOT INCLUDEDIR)

IF(NOT SYSTEMDDIR)
	SET(SYSTEMDDIR ${CMAKE_INSTALL_PREFIX}/lib/systemd/system)
ENDIF(NOT SYSTEMDDIR)

SET(RSPAMD_DEFAULT_INCLUDE_PATHS "/opt;/usr;/usr/local;/opt/local;/usr/pkg;/opt/csw;/sw")
SET(RSPAMD_DEFAULT_LIBRARY_PATHS "/usr/local;/usr/pkg;/usr;/Library/Frameworks;/sw;/opt/local;/opt/csw;/opt")

IF(ENABLE_STATIC MATCHES "ON")
	MESSAGE(STATUS "Static build of rspamd implies that the target binary will be *GPL* licensed")
	SET(GPL_RSPAMD_BINARY 1)
	SET(CMAKE_SKIP_INSTALL_RPATH ON)
	SET(BUILD_STATIC 1)
	SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
	SET(BUILD_SHARED_LIBRARIES OFF)
	SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
	SET(LINK_TYPE "STATIC")
	SET(NO_SHARED "ON")
	# Dirty hack for cmake
	SET(CMAKE_EXE_LINK_DYNAMIC_C_FLAGS)       # remove -Wl,-Bdynamic
	SET(CMAKE_EXE_LINK_DYNAMIC_CXX_FLAGS)
	SET(CMAKE_SHARED_LIBRARY_C_FLAGS)         # remove -fPIC
	SET(CMAKE_SHARED_LIBRARY_CXX_FLAGS)
	SET(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS)    # remove -rdynamic
	SET(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS)
ELSE(ENABLE_STATIC MATCHES "ON")
	IF (NO_SHARED MATCHES "OFF")
		SET(LINK_TYPE "SHARED")
	ELSE(NO_SHARED MATCHES "OFF")
		SET(LINK_TYPE "STATIC")
	ENDIF (NO_SHARED MATCHES "OFF")
ENDIF (ENABLE_STATIC MATCHES "ON")

############################# INCLUDE SECTION #############################################

INCLUDE(CheckIncludeFiles)
INCLUDE(CheckFunctionExists)
INCLUDE(CheckSymbolExists)
INCLUDE(CheckCSourceCompiles)
INCLUDE(CheckCSourceRuns)
INCLUDE(CheckLibraryExists)
INCLUDE(CheckCCompilerFlag)
INCLUDE(CMakeParseArguments)

FIND_PACKAGE(PkgConfig REQUIRED)
FIND_PACKAGE(Perl REQUIRED)

############################# MACRO SECTION #############################################

# Find lua installation
MACRO(FindLua)
	# Find lua libraries
	UNSET(LUA_INCLUDE_DIR CACHE)
	UNSET(LUA_LIBRARY CACHE)
	CMAKE_PARSE_ARGUMENTS(LUA "" "VERSION_MAJOR;VERSION_MINOR;ROOT" "" ${ARGN})

	IF(NOT LUA_VERSION_MAJOR OR NOT LUA_VERSION_MINOR)
		MESSAGE(FATAL_ERROR "Invalid FindLua invocation: ${ARGN}")
	ENDIF()

	IF(ENABLE_LUAJIT MATCHES "ON")
		MESSAGE(STATUS "Check for luajit ${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}")
		FIND_PATH(LUA_INCLUDE_DIR luajit.h
		  HINTS
		  "${RSPAMD_SEARCH_PATH}" "${LUA_ROOT}"
		  $ENV{LUA_DIR}
		  PATH_SUFFIXES "include/luajit-2.0"
				"include/luajit-2.1"
						"include/luajit${LUA_VERSION_MAJOR}${LUA_VERSION_MINOR}"
						"include/luajit${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
						"include/luajit-${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
						"include/luajit-${LUA_VERSION_MAJOR}_${LUA_VERSION_MINOR}-2.0"
						"include/luajit-${LUA_VERSION_MAJOR}_${LUA_VERSION_MINOR}-2.1"
						"include/luajit"
						"include/lua${LUA_VERSION_MAJOR}${LUA_VERSION_MINOR}"
						"include/lua${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
						"include/lua-${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
						include/lua include
		  PATHS ${RSPAMD_DEFAULT_INCLUDE_PATHS}
		)
		FIND_LIBRARY(LUA_LIBRARY
			NAMES luajit
				"luajit-2.0"
				"luajit2.0"
				"luajit${LUA_VERSION_MAJOR}${LUA_VERSION_MINOR}"
				"luajit${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
				"luajit-${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
			HINTS
				"${RSPAMD_SEARCH_PATH}" "${LUA_ROOT}"
				$ENV{LUA_DIR}
			PATH_SUFFIXES lib64 lib
			PATHS ${RSPAMD_DEFAULT_LIBRARY_PATHS}
			DOC "Lua library"
		)

		IF(NOT LUA_LIBRARY OR NOT LUA_INCLUDE_DIR)
			MESSAGE(STATUS "Fallback from luajit to plain lua")
			SET(ENABLE_LUAJIT "OFF")
			MESSAGE(STATUS "Check for lua ${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}")
			FIND_PATH(LUA_INCLUDE_DIR lua.h
			  HINTS
			  "${RSPAMD_SEARCH_PATH}" "${LUA_ROOT}"
			  $ENV{LUA_DIR}
			  PATH_SUFFIXES "include/lua${LUA_VERSION_MAJOR}${LUA_VERSION_MINOR}"
							"include/lua${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
							"include/lua-${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
							include/lua include
			  PATHS ${RSPAMD_DEFAULT_INCLUDE_PATHS}
			)
			FIND_LIBRARY(LUA_LIBRARY
				NAMES lua
					"lua${LUA_VERSION_MAJOR}${LUA_VERSION_MINOR}"
					"lua${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
					"lua-${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
				HINTS
					"${RSPAMD_SEARCH_PATH}" "${LUA_ROOT}"
					$ENV{LUA_DIR}
				PATH_SUFFIXES lib64 lib
				PATHS ${RSPAMD_DEFAULT_LIBRARY_PATHS}
				DOC "Lua library"
			)
		ELSE()
			SET(WITH_LUAJIT 1)
		ENDIF()
	ELSE(ENABLE_LUAJIT MATCHES "ON")
		MESSAGE(STATUS "Check for lua ${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}")
		FIND_PATH(LUA_INCLUDE_DIR lua.h
		  HINTS
		  "${RSPAMD_SEARCH_PATH}" "${LUA_ROOT}"
		  $ENV{LUA_DIR}
		  PATH_SUFFIXES "include/lua${LUA_VERSION_MAJOR}${LUA_VERSION_MINOR}"
						"include/lua${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
						"include/lua-${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
						include/lua include
		  PATHS ${RSPAMD_DEFAULT_INCLUDE_PATHS}
		)
		FIND_LIBRARY(LUA_LIBRARY
			NAMES lua
				"lua${LUA_VERSION_MAJOR}${LUA_VERSION_MINOR}"
				"lua${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
				"lua-${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}"
			HINTS
				"${RSPAMD_SEARCH_PATH}" "${LUA_ROOT}"
				$ENV{LUA_DIR}
			PATH_SUFFIXES lib64 lib
			PATHS ${RSPAMD_DEFAULT_LIBRARY_PATHS}
			DOC "Lua library"
		)
	ENDIF(ENABLE_LUAJIT MATCHES "ON")

	IF(LUA_LIBRARY AND LUA_INCLUDE_DIR)
		SET(LUA_FOUND 1)
		IF(NOT LUA_VERSION_MAJOR OR NOT LUA_VERSION_MINOR)
			SET(LUA_VERSION_MAJOR ${LUA_VERSION_MAJOR})
			SET(LUA_VERSION_MINOR ${LUA_VERSION_MINOR})
		ENDIF(NOT LUA_VERSION_MAJOR OR NOT LUA_VERSION_MINOR)
		IF(ENABLE_LUAJIT MATCHES "ON")
			MESSAGE(STATUS "Found luajit ${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR} in lib:${LUA_LIBRARY}, headers:${LUA_INCLUDE_DIR}")
		ELSE(ENABLE_LUAJIT MATCHES "ON")
			MESSAGE(STATUS "Found lua ${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR} in lib:${LUA_LIBRARY}, headers:${LUA_INCLUDE_DIR}")
		ENDIF(ENABLE_LUAJIT MATCHES "ON")
	ENDIF(LUA_LIBRARY AND LUA_INCLUDE_DIR)
ENDMACRO()

FUNCTION(INSTALL_IF_NOT_EXISTS src dest destname suffix)
  IF(NOT IS_ABSOLUTE "${src}")
	SET(src "${CMAKE_CURRENT_SOURCE_DIR}/${src}")
  ENDIF()
  GET_FILENAME_COMPONENT(src_name "${src}" NAME)
  GET_FILENAME_COMPONENT(dest_name "${destname}" NAME)
  IF(NOT IS_ABSOLUTE "${dest}")
	SET(dest "${CMAKE_INSTALL_PREFIX}/${dest}")
  ENDIF()
  INSTALL(CODE "
	IF(NOT EXISTS \"\$ENV{DESTDIR}${dest}/${dest_name}${suffix}\")
	  #FILE(INSTALL \"${src}\" DESTINATION \"${dest}\")
	  MESSAGE(STATUS \"Installing: \$ENV{DESTDIR}${dest}/${dest_name}${suffix}\")
	  EXECUTE_PROCESS(COMMAND \${CMAKE_COMMAND} -E copy \"${src}\"
					  \"\$ENV{DESTDIR}${dest}/${dest_name}${suffix}\"
					  RESULT_VARIABLE copy_result
					  ERROR_VARIABLE error_output)
	  IF(copy_result)
		MESSAGE(FATAL_ERROR \${error_output})
	  ENDIF()
	ELSE()
	  MESSAGE(STATUS \"Skipping  : \$ENV{DESTDIR}${dest}/${dest_name}${suffix}\")
	ENDIF()
  ")
ENDFUNCTION(INSTALL_IF_NOT_EXISTS)

# Process required package by using FindPackage and calling for INCLUDE_DIRECTORIES and
# setting list of required libraries
# Usage:
# ProcessPackage(VAR [OPTIONAL] [ROOT path] [INCLUDE path]
#	[LIBRARY path] [INCLUDE_SUFFIXES path1 path2 ...] [LIB_SUFFIXES path1 path2 ...]
#	[MODULES module1 module2 ...])
# params:
# OPTIONAL - do not fail if a package has not been found
# ROOT - defines root directory for a package
# INCLUDE - name of the include file to check
# LIBRARY - name of the library to check
# INCLUDE_SUFFIXES - list of include suffixes (relative to ROOT)
# LIB_SUFFIXES - list of library suffixes
# MODULES - modules to search using pkg_config
MACRO(ProcessPackage PKG_NAME)

	CMAKE_PARSE_ARGUMENTS(PKG "OPTIONAL" "ROOT;INCLUDE"
		"LIBRARY;INCLUDE_SUFFIXES;LIB_SUFFIXES;MODULES;LIB_OUTPUT" ${ARGN})

	IF(NOT PKG_LIBRARY)
		SET(PKG_LIBRARY "${PKG_NAME}")
	ENDIF()
	IF(NOT PKG_INCLUDE)
		SET(PKG_INCLUDE "${PKG_NAME}.h")
	ENDIF()
	IF(NOT PKG_LIB_OUTPUT)
		SET(PKG_LIB_OUTPUT RSPAMD_REQUIRED_LIBRARIES)
	ENDIF()

	IF(NOT PKG_ROOT AND PKG_MODULES)
		PKG_SEARCH_MODULE(${PKG_NAME} ${PKG_MODULES})
	ENDIF()

	IF(${PKG_NAME}_FOUND)
		MESSAGE(STATUS "Found package ${PKG_NAME} in pkg-config modules ${PKG_MODULES}")
		SET(WITH_${PKG_NAME} 1 CACHE INTERNAL "")
		IF(ENABLE_STATIC MATCHES "ON")
			SET(_XPREFIX "${PKG_NAME}_STATIC")
		ELSE(ENABLE_STATIC MATCHES "ON")
			SET(_XPREFIX "${PKG_NAME}")
		ENDIF(ENABLE_STATIC MATCHES "ON")
		FOREACH(_arg ${${_XPREFIX}_INCLUDE_DIRS})
			INCLUDE_DIRECTORIES("${_arg}")
			SET(${PKG_NAME}_INCLUDE "${_arg}" CACHE INTERNAL "")
		ENDFOREACH(_arg ${${_XPREFIX}_INCLUDE_DIRS})
		FOREACH(_arg ${${_XPREFIX}_LIBRARY_DIRS})
			LINK_DIRECTORIES("${_arg}")
			SET(${PKG_NAME}_LIBRARY_PATH "${_arg}" CACHE INTERNAL "")
		ENDFOREACH(_arg ${${_XPREFIX}_LIBRARY_DIRS})
		# Handle other CFLAGS and LDFLAGS
		FOREACH(_arg ${${_XPREFIX}_CFLAGS_OTHER})
			SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${_arg}")
			SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${_arg}")
		ENDFOREACH(_arg ${${_XPREFIX}_CFLAGS_OTHER})
		FOREACH(_arg ${${_XPREFIX}_LDFLAGS_OTHER})
			SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${_arg}")
		ENDFOREACH(_arg ${${_XPREFIX}_LDFLAGS_OTHER})
		LIST(APPEND ${PKG_LIB_OUTPUT} "${${_XPREFIX}_LIBRARIES}")
		INCLUDE_DIRECTORIES(${${_XPREFIX}_INCLUDEDIR})
	ELSE()
		IF(NOT ${PKG_NAME}_GUESSED)
			# Try some more heuristic
			FIND_LIBRARY(_lib NAMES ${PKG_LIBRARY}
						HINTS ${PKG_ROOT} ${RSPAMD_SEARCH_PATH}
						PATH_SUFFIXES ${PKG_LIB_SUFFIXES} lib64 lib
						PATHS ${RSPAMD_DEFAULT_LIBRARY_PATHS})
			IF(NOT _lib)
				IF(PKG_OPTIONAL)
					MESSAGE(STATUS "Cannot find library ${PKG_LIBRARY} for package ${PKG_NAME}, ignoring")
				ELSE()
					MESSAGE(FATAL_ERROR "Cannot find library ${PKG_LIBRARY} for package ${PKG_NAME}")
				ENDIF()
			ENDIF(NOT _lib)

			FIND_PATH(_incl ${PKG_INCLUDE}
							HINTS ${PKG_ROOT} ${RSPAMD_SEARCH_PATH}
							PATH_SUFFIXES ${PKG_INCLUDE_SUFFIXES} include
							PATHS 	{RSPAMD_DEFAULT_INCLUDE_PATHS})
			IF(NOT _incl)
				IF(PKG_OPTIONAL)
					MESSAGE(STATUS "Cannot find header ${PKG_INCLUDE} for package ${PKG_NAME}")
				ELSE()
					MESSAGE(FATAL_ERROR "Cannot find header ${PKG_INCLUDE} for package ${PKG_NAME}")
				ENDIF()
			ENDIF(NOT _incl)

			IF(_incl AND _lib)
				# We need to apply heuristic to find the real dir name
				STRING(REGEX REPLACE "/[^/]+$" "" _incl_path "${PKG_INCLUDE}")
				STRING(REGEX REPLACE "${_incl_path}/$" "" _stripped_incl "${_incl}")
				GET_FILENAME_COMPONENT(_lib_path "${_lib}" PATH)
				INCLUDE_DIRECTORIES("${_stripped_incl}")
				LINK_DIRECTORIES("${_lib_path}")
				LIST(APPEND ${PKG_LIB_OUTPUT} ${_lib})
				SET(${PKG_NAME}_INCLUDE "${_stripped_incl}" CACHE INTERNAL "")
				SET(${PKG_NAME}_LIBRARY_PATH "${_lib_path}" CACHE INTERNAL "")
				SET(${PKG_NAME}_LIBRARY "${_lib}" CACHE INTERNAL "")
				SET(${PKG_NAME}_GUESSED 1 CACHE INTERNAL "")
				SET(WITH_${PKG_NAME} 1 CACHE INTERNAL "")
				MESSAGE(STATUS "Found package ${PKG_NAME} in '${_lib_path}' (${_lib}) and '${_stripped_incl}' (${PKG_INCLUDE}).")
			ENDIF()

		ELSE()
			MESSAGE(STATUS "Found package ${PKG_NAME} (cached)")
			INCLUDE_DIRECTORIES("${${PKG_NAME}_INCLUDE}")
			LINK_DIRECTORIES("${${PKG_NAME}_LIBRARY_PATH}")
			LIST(APPEND ${PKG_LIB_OUTPUT} "${${PKG_NAME}_LIBRARY}")
		ENDIF()
	ENDIF(${PKG_NAME}_FOUND)

	UNSET(_lib CACHE)
	UNSET(_incl CACHE)
ENDMACRO(ProcessPackage name)
############################# CONFIG SECTION #############################################
# Initial set

# Prefer local include dirs to system ones
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/"
		"${CMAKE_SOURCE_DIR}/src"
		"${CMAKE_SOURCE_DIR}/src/libutil"
		"${CMAKE_SOURCE_DIR}/src/libserver"
		"${CMAKE_SOURCE_DIR}/src/libmime"
		"${CMAKE_SOURCE_DIR}/src/libstat"
		"${CMAKE_SOURCE_DIR}/src/libcryptobox"
		"${CMAKE_SOURCE_DIR}/contrib/libucl"
		"${CMAKE_SOURCE_DIR}/contrib/replxx/include"
		"${CMAKE_SOURCE_DIR}/contrib/uthash"
		"${CMAKE_SOURCE_DIR}/contrib/http-parser"
		"${CMAKE_SOURCE_DIR}/contrib/fpconv"
		"${CMAKE_SOURCE_DIR}/contrib/libottery"
		"${CMAKE_SOURCE_DIR}/contrib/xxhash"
		"${CMAKE_SOURCE_DIR}/contrib/cdb"
		"${CMAKE_SOURCE_DIR}/contrib/snowball/include"
		"${CMAKE_SOURCE_DIR}/contrib/librdns"
		"${CMAKE_SOURCE_DIR}/contrib/aho-corasick"
		"${CMAKE_SOURCE_DIR}/contrib/lc-btrie"
		"${CMAKE_SOURCE_DIR}/contrib/lua-lpeg"
		"${CMAKE_BINARY_DIR}/src" #Stored in the binary dir
		"${CMAKE_BINARY_DIR}/src/libcryptobox")

SET(POE_LOOP "Loop::IO_Poll")
SET(TAR "tar")

# Platform specific configuration
IF(CMAKE_SYSTEM_NAME MATCHES "^.*BSD$|DragonFly")
	ADD_DEFINITIONS(-DFREEBSD -D_BSD_SOURCE)
	CONFIGURE_FILE(freebsd/rspamd.sh.in freebsd/rspamd @ONLY)
	MESSAGE(STATUS "Configuring for BSD system")
	# Find util library
	ProcessPackage(LIBUTIL LIBRARY util INCLUDE libutil.h
		ROOT ${LIBUTIL_ROOT_DIR} OPTIONAL)
	IF(WITH_LIBUTIL)
		SET(HAVE_LIBUTIL_H 1)
		LIST(APPEND CMAKE_REQUIRED_LIBRARIES util)
		CHECK_FUNCTION_EXISTS(pidfile_open HAVE_PIDFILE)
		CHECK_FUNCTION_EXISTS(pidfile_fileno HAVE_PIDFILE_FILENO)
	ENDIF()
	IF(CMAKE_SYSTEM_NAME MATCHES "^NetBSD$")
		LIST(APPEND CMAKE_REQUIRED_LIBRARIES rt)
	ENDIF()
	SET(POE_LOOP "Loop::Kqueue")
	SET(TAR "gtar")
ENDIF()

IF(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
	ADD_DEFINITIONS(-D_BSD_SOURCE -DDARWIN)
	SET(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "${CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS} -undefined dynamic_lookup")
	IF(ENABLE_LUAJIT MATCHES "ON")
		SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pagezero_size 10000 -image_base 100000000")
	ENDIF(ENABLE_LUAJIT MATCHES "ON")
	MESSAGE(STATUS "Configuring for Darwin")
	SET(TAR "gnutar")
	SET(CMAKE_FIND_FRAMEWORK "NEVER")
ENDIF(CMAKE_SYSTEM_NAME STREQUAL "Darwin")

IF(CMAKE_SYSTEM_NAME STREQUAL "Linux")
	ADD_DEFINITIONS(-D_GNU_SOURCE -DLINUX)
	# Workaround with architecture specific includes
	#IF(IS_DIRECTORY "/usr/include/${CMAKE_SYSTEM_PROCESSOR}-linux-gnu/")
	#	INCLUDE_DIRECTORIES("/usr/include/${CMAKE_SYSTEM_PROCESSOR}-linux-gnu/")
	#	LIST(APPEND CMAKE_REQUIRED_INCLUDES "/usr/include/${CMAKE_SYSTEM_PROCESSOR}-linux-gnu/")
	#ENDIF(IS_DIRECTORY "/usr/include/${CMAKE_SYSTEM_PROCESSOR}-linux-gnu/")

	LIST(APPEND CMAKE_REQUIRED_LIBRARIES rt)
	LIST(APPEND CMAKE_REQUIRED_LIBRARIES dl)
	LIST(APPEND CMAKE_REQUIRED_LIBRARIES resolv)
	MESSAGE(STATUS "Configuring for Linux")
	IF(EXISTS "/etc/debian_version")
		SET(LINUX_START_SCRIPT "rspamd_debian.in")
	ELSE(EXISTS "/etc/debian_version")
		SET(LINUX_START_SCRIPT "rspamd_rh.in")
	ENDIF(EXISTS "/etc/debian_version")
	SET(POE_LOOP "XS::Loop::EPoll")
ENDIF(CMAKE_SYSTEM_NAME STREQUAL "Linux")

IF(CMAKE_SYSTEM_NAME STREQUAL "SunOS")

	IF("${CMAKE_C_COMPILER_ID}" MATCHES SunPro)
		SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Xa -xregs=no%frameptr -xstrconst -xc99")
		IF(ENABLE_OPTIMIZATION MATCHES "ON")
			SET(CMAKE_C_OPT_FLAGS "-fast -xdepend")
		ELSE(ENABLE_OPTIMIZATION MATCHES "ON")
			SET(CMAKE_C_OPT_FLAGS "-xO0")
		ENDIF(ENABLE_OPTIMIZATION MATCHES "ON")
	ENDIF("${CMAKE_C_COMPILER_ID}" MATCHES SunPro)

	ADD_DEFINITIONS(-D__EXTENSIONS__ -DSOLARIS -D_POSIX_SOURCE -D_POSIX_C_SOURCE=200112)
	LIST(APPEND CMAKE_REQUIRED_LIBRARIES rt)
	LIST(APPEND CMAKE_REQUIRED_LIBRARIES dl)
	LIST(APPEND CMAKE_REQUIRED_LIBRARIES resolv)
	LIST(APPEND CMAKE_REQUIRED_LIBRARIES nsl)
	LIST(APPEND CMAKE_REQUIRED_LIBRARIES socket)
	LIST(APPEND CMAKE_REQUIRED_LIBRARIES umem)
	# Ugly hack, but FindOpenSSL on Solaris does not link with libcrypto
	SET(CMAKE_VERBOSE_MAKEFILE ON)
	SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
	SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib:${RSPAMD_LIBDIR}")
ENDIF(CMAKE_SYSTEM_NAME STREQUAL "SunOS")

# Now find libraries and headers
LIST(APPEND RSPAMD_REQUIRED_LIBRARIES "m")
IF(ENABLE_LUAJIT MATCHES "ON")
	#ProcessPackage(LUAJIT luajit)
	SET(WITH_LUA 1)
	FindLua(VERSION_MAJOR "5" VERSION_MINOR "1" ROOT "${LUA_ROOT}")
	IF(NOT LUA_FOUND)
		MESSAGE(FATAL_ERROR "Lua not found, lua support is required")
	ELSE(NOT LUA_FOUND)
		SET(WITH_LUA 1)
		INCLUDE_DIRECTORIES("${LUA_INCLUDE_DIR}")
	ENDIF(NOT LUA_FOUND)
ELSE(ENABLE_LUAJIT MATCHES "ON")
	FindLua(VERSION_MAJOR "5" VERSION_MINOR "3" ROOT "${LUA_ROOT}")
	IF(NOT LUA_FOUND)
		FindLua(VERSION_MAJOR "5" VERSION_MINOR "2" ROOT "${LUA_ROOT}")
		IF(NOT LUA_FOUND)
				FindLua(VERSION_MAJOR "5" VERSION_MINOR "1" ROOT "${LUA_ROOT}")
		ENDIF(NOT LUA_FOUND)
	ENDIF(NOT LUA_FOUND)
	IF(NOT LUA_FOUND)
			MESSAGE(FATAL_ERROR "Lua not found, lua support is required")
	ELSE(NOT LUA_FOUND)
			SET(WITH_LUA 1)
			INCLUDE_DIRECTORIES("${LUA_INCLUDE_DIR}")
	ENDIF(NOT LUA_FOUND)
ENDIF(ENABLE_LUAJIT MATCHES "ON")

IF(ENABLE_JEMALLOC MATCHES "ON")
	ProcessPackage(JEMALLOC LIBRARY jemalloc_pic jemalloc INCLUDE jemalloc.h INCLUDE_SUFFIXES include/jemalloc
		ROOT ${JEMALLOC_ROOT_DIR})
	SET(WITH_JEMALLOC "1")
	LIST(APPEND RSPAMD_REQUIRED_LIBRARIES "-lpthread")
ENDIF()

IF(ENABLE_LIBUNWIND MATCHES "ON")
	ProcessPackage(LIBUNWIND LIBRARY unwind INCLUDE libunwind.h INCLUDE_SUFFIXES include/libunwind
			ROOT ${LIBUNWIND_ROOT_DIR} MODULES libunwind)
	SET(WITH_LIBUNWIND "1")
ENDIF()

ProcessPackage(GLIB2 LIBRARY glib-2.0 INCLUDE glib.h
	INCLUDE_SUFFIXES include/glib include/glib-2.0
	ROOT ${GLIB_ROOT_DIR} MODULES glib-2.0>=2.28)

IF(ENABLE_PCRE2 MATCHES "ON")
	ProcessPackage(PCRE LIBRARY pcre2 pcre2-8 INCLUDE pcre2.h INCLUDE_SUFFIXES include/pcre2
		ROOT ${PCRE_ROOT_DIR} MODULES pcre2 pcre2-8 libpcre2 libpcre2-8)
ELSE()
	ProcessPackage(PCRE LIBRARY pcre INCLUDE pcre.h INCLUDE_SUFFIXES include/pcre
		ROOT ${PCRE_ROOT_DIR} MODULES pcre libpcre pcre3 libpcre3)
ENDIF()

ProcessPackage(SQLITE3 LIBRARY sqlite3 INCLUDE sqlite3.h INCLUDE_SUFFIXES include/sqlite3 include/sqlite
	ROOT ${SQLITE3_ROOT_DIR} MODULES sqlite3 sqlite)
ProcessPackage(ICUDATA LIBRARY icudata INCLUDE unicode/ucnv.h
	ROOT ${ICU_ROOT_DIR} MODULES icu-i18n)
ProcessPackage(ICUC LIBRARY icuuc INCLUDE unicode/ucnv.h
	ROOT ${ICU_ROOT_DIR} MODULES icu-i18n)
ProcessPackage(ICUI18N LIBRARY icui18n INCLUDE unicode/ucnv.h
	ROOT ${ICU_ROOT_DIR} MODULES icu-i18n)
ProcessPackage(LIBCRYPT LIBRARY crypto INCLUDE openssl/evp.h
	ROOT ${OPENSSL_ROOT_DIR} MODULES openssl libcrypt)
ProcessPackage(LIBSSL LIBRARY ssl INCLUDE openssl/ssl.h
	ROOT ${OPENSSL_ROOT_DIR} MODULES openssl libssl)
ProcessPackage(LIBZ LIBRARY z INCLUDE zlib.h INCLUDE_SUFFIXES include/zlib
		ROOT ${LIBZ_ROOT_DIR} MODULES z)
ProcessPackage(SODIUM LIBRARY sodium INCLUDE sodium.h
		INCLUDE_SUFFIXES include/libsodium include/sodium
		ROOT ${LIBSODIUM_ROOT_DIR} MODULES libsodium>=1.0.0)

IF(ENABLE_HYPERSCAN MATCHES "ON")
	ProcessPackage(HYPERSCAN LIBRARY hs INCLUDE hs.h INCLUDE_SUFFIXES
			hs include/hs
			ROOT ${HYPERSCAN_ROOT_DIR} MODULES libhs)
	SET(WITH_HYPERSCAN 1)

	# For static linking with Hyperscan we need to link using CXX
	IF (ENABLE_HYPERSCAN MATCHES "ON")
		IF(${HYPERSCAN_LIBRARY} MATCHES ".*[.]a$" OR STATIC_HYPERSCAN)
			ENABLE_LANGUAGE(CXX)
			SET(USE_CXX_LINKER 1)
		ENDIF()
	ENDIF()
ENDIF()

#Check for openssl (required for dkim)
SET(HAVE_OPENSSL 1)

# Google performance tools

IF(ENABLE_GPERF_TOOLS MATCHES "ON")
	ProcessPackage(GPERF LIBRARY profiler INCLUDE profiler.h INCLUDE_SUFFIXES include/google
		ROOT ${GPERF_ROOT_DIR})
	SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-omit-frame-pointer")
	SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-omit-frame-pointer")
	SET(WITH_GPERF_TOOLS 1)
ENDIF(ENABLE_GPERF_TOOLS MATCHES "ON")

CHECK_C_COMPILER_FLAG(-Wall SUPPORT_WALL)
CHECK_C_COMPILER_FLAG(-W SUPPORT_W)
CHECK_C_COMPILER_FLAG(-Wpointer-arith SUPPORT_WPOINTER)
CHECK_C_COMPILER_FLAG(-Wno-unused-parameter SUPPORT_WPARAM)
CHECK_C_COMPILER_FLAG(-Wno-unused-function SUPPORT_WFUNCTION)
CHECK_C_COMPILER_FLAG(-Wno-strict-aliasing SUPPORT_WSTRICT_ALIASING)
CHECK_C_COMPILER_FLAG(-Wunused-variable SUPPORT_WUNUSED_VAR)
CHECK_C_COMPILER_FLAG(-Wno-pointer-sign SUPPORT_WPOINTER_SIGN)
CHECK_C_COMPILER_FLAG(-Wno-sign-compare SUPPORT_WSIGN_COMPARE)
CHECK_C_COMPILER_FLAG(-Wstrict-prototypes SUPPORT_WSTRICT_PROTOTYPES)
CHECK_C_COMPILER_FLAG(-pedantic SUPPORT_PEDANTIC_FLAG)
CHECK_C_COMPILER_FLAG(-Wno-unused-const-variable SUPPORT_WNO_UNUSED_CONST)
# GCC 6 specific
CHECK_C_COMPILER_FLAG(-Wnull-dereference SUPPORT_WNULL_DEREFERENCE)
CHECK_C_COMPILER_FLAG(-Wduplicated-cond SUPPORT_WDUPLICATED_COND)
# GCC 7 specific
CHECK_C_COMPILER_FLAG(-Wimplicit-fallthrough SUPPORT_WIMPLICIT_FALLTHROUGH)

IF(SUPPORT_W)
	ADD_COMPILE_OPTIONS("-W")
ENDIF(SUPPORT_W)
IF(SUPPORT_WALL)
	ADD_COMPILE_OPTIONS("-Wall")
ENDIF(SUPPORT_WALL)
IF(SUPPORT_WPOINTER)
	ADD_COMPILE_OPTIONS("-Wpointer-arith")
ENDIF(SUPPORT_WPOINTER)
IF(SUPPORT_WPARAM)
	ADD_COMPILE_OPTIONS("-Wno-unused-parameter")
ENDIF(SUPPORT_WPARAM)
IF(SUPPORT_WFUNCTION)
	ADD_COMPILE_OPTIONS("-Wno-unused-function")
ENDIF(SUPPORT_WFUNCTION)
IF(SUPPORT_WUNUSED_VAR)
	ADD_COMPILE_OPTIONS("-Wunused-variable")
ENDIF(SUPPORT_WUNUSED_VAR)
IF(SUPPORT_WPOINTER_SIGN)
	ADD_COMPILE_OPTIONS("-Wno-pointer-sign")
ENDIF(SUPPORT_WPOINTER_SIGN)
IF(SUPPORT_WSTRICT_PROTOTYPES)
	ADD_COMPILE_OPTIONS("-Wstrict-prototypes")
ENDIF(SUPPORT_WSTRICT_PROTOTYPES)
IF(SUPPORT_WSTRICT_ALIASING)
	ADD_COMPILE_OPTIONS("-Wno-strict-aliasing")
	ADD_COMPILE_OPTIONS("-fno-strict-aliasing")
ENDIF(SUPPORT_WSTRICT_ALIASING)
#IF(SUPPORT_PEDANTIC_FLAG)
#	SET(CMAKE_C_WARN_FLAGS "${CMAKE_C_WARN_FLAGS} -pedantic")
#ENDIF(SUPPORT_PEDANTIC_FLAG)
IF(SUPPORT_WNULL_DEREFERENCE)
	ADD_COMPILE_OPTIONS("-Wnull-dereference")
ENDIF()
IF(SUPPORT_WDUPLICATED_COND)
	ADD_COMPILE_OPTIONS("-Wduplicated-cond")
ENDIF()
IF(SUPPORT_WLOGICAL_OP)
	ADD_COMPILE_OPTIONS("-Wlogical-op")
ENDIF()
IF(SUPPORT_WNO_UNUSED_CONST)
	ADD_COMPILE_OPTIONS("-Wno-unused-const-variable")
ENDIF()
IF(SUPPORT_WSIGN_COMPARE)
	ADD_COMPILE_OPTIONS("-Wno-sign-compare")
ENDIF()
IF(SUPPORT_WIMPLICIT_FALLTHROUGH)
	ADD_COMPILE_OPTIONS("-Wno-implicit-fallthrough")
ENDIF(SUPPORT_WIMPLICIT_FALLTHROUGH)

CHECK_C_COMPILER_FLAG(-fPIC SUPPORT_FPIC)
IF(SUPPORT_FPIC)
	ADD_COMPILE_OPTIONS("-fPIC")
ENDIF(SUPPORT_FPIC)

 # Optimization flags
IF(NOT CMAKE_C_OPT_FLAGS)
	IF(ENABLE_OPTIMIZATION MATCHES "ON")
	CHECK_C_COMPILER_FLAG(-flto SUPPORT_FLTO)
	IF(SUPPORT_FLTO)
		IF(NOT CMAKE_GCC_AR OR NOT CMAKE_GCC_RANLIB)
			FIND_PROGRAM(CMAKE_GCC_AR NAMES "gcc-ar")
			FIND_PROGRAM(CMAKE_GCC_RANLIB NAMES "gcc-ranlib")
			MARK_AS_ADVANCED(CMAKE_GCC_AR CMAKE_GCC_RANLIB)
		ENDIF()
		IF(CMAKE_GCC_AR AND CMAKE_GCC_RANLIB)
			SET(CMAKE_C_OPT_FLAGS "-g -O3 -flto")
			SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -flto")
			SET(CMAKE_C_ARCHIVE_CREATE "${CMAKE_GCC_AR} cr <TARGET> <LINK_FLAGS> <OBJECTS>")
			SET(CMAKE_C_ARCHIVE_APPEND "${CMAKE_GCC_AR} r <TARGET> <LINK_FLAGS> <OBJECTS>")
			SET(CMAKE_C_ARCHIVE_FINISH "${CMAKE_GCC_RANLIB} <TARGET>")
			SET(CMAKE_CXX_ARCHIVE_CREATE "${CMAKE_GCC_AR} cr <TARGET> <LINK_FLAGS> <OBJECTS>")
			SET(CMAKE_CXX_ARCHIVE_APPEND "${CMAKE_GCC_AR} r <TARGET> <LINK_FLAGS> <OBJECTS>")
			SET(CMAKE_CXX_ARCHIVE_FINISH "${CMAKE_GCC_RANLIB} <TARGET>")
		ENDIF()
	ELSE()
		SET(CMAKE_C_OPT_FLAGS "-g -O3")
	ENDIF()
	ELSE(ENABLE_OPTIMIZATION MATCHES "ON")
		IF(ENABLE_FULL_DEBUG MATCHES "ON")
			ADD_DEFINITIONS(-DFULL_DEBUG)
			SET(CMAKE_C_OPT_FLAGS "-g -O0")
		ELSE(ENABLE_FULL_DEBUG MATCHES "ON")
			SET(CMAKE_C_OPT_FLAGS "-g -O2")
		ENDIF(ENABLE_FULL_DEBUG MATCHES "ON")
	ENDIF(ENABLE_OPTIMIZATION MATCHES "ON")
ENDIF(NOT CMAKE_C_OPT_FLAGS)

IF(ENABLE_COVERAGE)
	SET(CMAKE_C_OPT_FLAGS "-g -O0")
	SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --coverage")
	SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --coverage")
	SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --coverage")
ENDIF(ENABLE_COVERAGE)

IF(ENABLE_LUA_TRACE)
	SET(WITH_LUA_TRACE 1)
ENDIF(ENABLE_LUA_TRACE)

SET(CMAKE_C_FLAGS "${CMAKE_C_OPT_FLAGS} ${CMAKE_C_FLAGS}")
SET(CMAKE_CXX_FLAGS "${CMAKE_C_OPT_FLAGS} ${CMAKE_CXX_FLAGS}")

ADD_DEFINITIONS(-DHAVE_CONFIG_H)

# Check platform specific includes
CHECK_INCLUDE_FILES(sys/types.h HAVE_SYS_TYPES_H)
CHECK_INCLUDE_FILES(sys/time.h  HAVE_SYS_TIME_H)
CHECK_INCLUDE_FILES(sys/uio.h   HAVE_SYS_UIO_H)

CHECK_INCLUDE_FILES(fcntl.h     HAVE_FCNTL_H)
CHECK_INCLUDE_FILES(math.h      HAVE_MATH_H)
CHECK_INCLUDE_FILES(stdio.h     HAVE_STDIO_H)
CHECK_INCLUDE_FILES(stdlib.h    HAVE_STDLIB_H)
CHECK_INCLUDE_FILES(string.h    HAVE_STRING_H)
CHECK_INCLUDE_FILES(strings.h   HAVE_STRINGS_H)
CHECK_INCLUDE_FILES(time.h      HAVE_TIME_H)
CHECK_INCLUDE_FILES(unistd.h    HAVE_UNISTD_H)
CHECK_INCLUDE_FILES(sysexits.h  HAVE_SYSEXITS_H)
CHECK_INCLUDE_FILES(stdint.h  HAVE_STDINT_H)
CHECK_INCLUDE_FILES(inttypes.h  HAVE_INTTYPES_H)
CHECK_INCLUDE_FILES(stdbool.h  HAVE_STDBOOL_H)
CHECK_INCLUDE_FILES(endian.h  HAVE_ENDIAN_H)
CHECK_INCLUDE_FILES(sys/endian.h  HAVE_SYS_ENDIAN_H)
CHECK_INCLUDE_FILES(machine/endian.h  HAVE_MACHINE_ENDIAN_H)
CHECK_INCLUDE_FILES(sys/queue.h  HAVE_SYS_QUEUE_H)
CHECK_INCLUDE_FILES(sys/socket.h  HAVE_SYS_SOCKET_H)
CHECK_INCLUDE_FILES(sys/mman.h  HAVE_SYS_MMAN_H)
CHECK_INCLUDE_FILES(sys/un.h  HAVE_SYS_UN_H)
CHECK_INCLUDE_FILES(sys/stat.h  HAVE_SYS_STAT_H)
CHECK_INCLUDE_FILES(sys/wait.h  HAVE_SYS_WAIT_H)
CHECK_INCLUDE_FILES(sys/param.h  HAVE_SYS_PARAM_H)
CHECK_INCLUDE_FILES(sys/cdefs.h  HAVE_SYS_CDEFS_H)
CHECK_INCLUDE_FILES(sys/file.h  HAVE_SYS_FILE_H)
CHECK_INCLUDE_FILES(sys/utsname.h  HAVE_SYS_UTSNAME_H)
CHECK_INCLUDE_FILES(sys/resource.h  HAVE_SYS_RESOURCE_H)
CHECK_INCLUDE_FILES(netinet/in.h  HAVE_NETINET_IN_H)
CHECK_INCLUDE_FILES(netinet/tcp.h  HAVE_NETINET_TCP_H)
CHECK_INCLUDE_FILES(arpa/inet.h  HAVE_ARPA_INET_H)
CHECK_INCLUDE_FILES(netdb.h  HAVE_NETDB_H)
CHECK_INCLUDE_FILES(syslog.h HAVE_SYSLOG_H)
CHECK_INCLUDE_FILES(siginfo.h HAVE_SIGINFO_H)
CHECK_INCLUDE_FILES(locale.h HAVE_LOCALE_H)
CHECK_INCLUDE_FILES(libgen.h HAVE_LIBGEN_H)
CHECK_INCLUDE_FILES(search.h HAVE_SEARCH_H)
CHECK_INCLUDE_FILES(pwd.h HAVE_PWD_H)
CHECK_INCLUDE_FILES(grp.h HAVE_GRP_H)
CHECK_INCLUDE_FILES(glob.h HAVE_GLOB_H)
CHECK_INCLUDE_FILES(poll.h HAVE_POLL_H)
CHECK_INCLUDE_FILES(readpassphrase.h HAVE_READPASSPHRASE_H)
CHECK_INCLUDE_FILES(termios.h HAVE_TERMIOS_H)
CHECK_INCLUDE_FILES(paths.h HAVE_PATHS_H)
CHECK_INCLUDE_FILES(ctype.h HAVE_CTYPE_H)
CHECK_INCLUDE_FILES(unistd.h HAVE_UNISTD_H)
CHECK_INCLUDE_FILES(cpuid.h HAVE_CPUID_H)
CHECK_INCLUDE_FILES(dirent.h HAVE_DIRENT_H)
CHECK_INCLUDE_FILES(stropts.h HAVE_STROPS_H)
CHECK_INCLUDE_FILES(sys/ioctl.h HAVE_SYS_IOCTL_H)
CHECK_INCLUDE_FILES(ucontext.h HAVE_UCONTEXT_H)
CHECK_INCLUDE_FILES(sys/ucontext.h HAVE_SYS_UCONTEXT_H) # OSX specific

# Check platform API
CHECK_FUNCTION_EXISTS(setproctitle HAVE_SETPROCTITLE)
CHECK_FUNCTION_EXISTS(getpagesize HAVE_GETPAGESIZE)
CHECK_FUNCTION_EXISTS(nanosleep HAVE_NANOSLEEP)
CHECK_FUNCTION_EXISTS(vfork HAVE_VFORK)
CHECK_FUNCTION_EXISTS(wait4 HAVE_WAIT4)
CHECK_FUNCTION_EXISTS(waitpid HAVE_WAITPID)
CHECK_FUNCTION_EXISTS(flock HAVE_FLOCK)
CHECK_LIBRARY_EXISTS(m tanhl "" HAVE_TANHL)
CHECK_LIBRARY_EXISTS(m tanh "" HAVE_TANH)
CHECK_LIBRARY_EXISTS(m expl "" HAVE_EXPL)
CHECK_LIBRARY_EXISTS(m exp2l "" HAVE_EXP2L)
CHECK_FUNCTION_EXISTS(sendfile HAVE_SENDFILE)
CHECK_FUNCTION_EXISTS(mkstemp HAVE_MKSTEMP)
CHECK_FUNCTION_EXISTS(setitimer HAVE_SETITIMER)
CHECK_FUNCTION_EXISTS(inet_pton HAVE_INET_PTON)
CHECK_FUNCTION_EXISTS(clock_gettime HAVE_CLOCK_GETTIME)
CHECK_C_SOURCE_COMPILES(
		"#include <time.h>
		extern char *tzname[2];
		extern long timezone;
		extern int daylight;
	int main(int argc, char** argv) {
		tzset();
		return timezone;
	}" HAVE_SANE_TZSET)

IF(WITH_ICONV)
	CHECK_C_SOURCE_COMPILES("
#include <iconv.h>
int main(){
	iconv_t conv = 0;
	const char* in = 0;
	size_t ilen = 0;
	char* out = 0;
	size_t olen = 0;
	iconv(conv, &in, &ilen, &out, &olen);
	return 0;
}
" ICONV_SECOND_ARGUMENT_IS_CONST)
ENDIF(WITH_ICONV)

# Check macros
CHECK_SYMBOL_EXISTS(PATH_MAX limits.h HAVE_PATH_MAX)
CHECK_SYMBOL_EXISTS(MAXPATHLEN sys/param.h HAVE_MAXPATHLEN)
CHECK_SYMBOL_EXISTS(MAP_SHARED sys/mman.h HAVE_MMAP_SHARED)
CHECK_SYMBOL_EXISTS(MAP_ANON sys/mman.h HAVE_MMAP_ANON)
CHECK_SYMBOL_EXISTS(MAP_NOCORE sys/mman.h HAVE_MMAP_NOCORE)
CHECK_SYMBOL_EXISTS(O_DIRECT fcntl.h HAVE_O_DIRECT)
CHECK_SYMBOL_EXISTS(IPV6_V6ONLY "sys/socket.h;netinet/in.h" HAVE_IPV6_V6ONLY)
CHECK_SYMBOL_EXISTS(posix_fadvise fcntl.h HAVE_FADVISE)
CHECK_SYMBOL_EXISTS(posix_fallocate fcntl.h HAVE_POSIX_FALLOCATE)
CHECK_SYMBOL_EXISTS(fallocate fcntl.h HAVE_FALLOCATE)
CHECK_SYMBOL_EXISTS(fdatasync unistd.h HAVE_FDATASYNC)
CHECK_SYMBOL_EXISTS(_SC_NPROCESSORS_ONLN unistd.h HAVE_SC_NPROCESSORS_ONLN)
CHECK_SYMBOL_EXISTS(setbit sys/param.h PARAM_H_HAS_BITSET)
CHECK_SYMBOL_EXISTS(getaddrinfo "sys/types.h;sys/socket.h;netdb.h" HAVE_GETADDRINFO)
CHECK_SYMBOL_EXISTS(sched_yield "sched.h" HAVE_SCHED_YIELD)
CHECK_SYMBOL_EXISTS(__get_cpuid "cpuid.h" HAVE_GET_CPUID)
CHECK_SYMBOL_EXISTS(nftw "sys/types.h;ftw.h" HAVE_NFTW)
IF(ENABLE_PCRE2 MATCHES "ON")
	LIST(APPEND CMAKE_REQUIRED_INCLUDES "${PCRE_INCLUDE}")
	CHECK_SYMBOL_EXISTS(PCRE2_CONFIG_JIT "pcre2.h" HAVE_PCRE_JIT)
ELSE()
	LIST(APPEND CMAKE_REQUIRED_INCLUDES "${PCRE_INCLUDE}")
	CHECK_SYMBOL_EXISTS(PCRE_CONFIG_JIT "pcre.h" HAVE_PCRE_JIT)
ENDIF()
CHECK_SYMBOL_EXISTS(SOCK_SEQPACKET "sys/types.h;sys/socket.h" HAVE_SOCK_SEQPACKET)
CHECK_SYMBOL_EXISTS(I_SETSIG "sys/types.h;sys/ioctl.h" HAVE_SETSIG)
CHECK_SYMBOL_EXISTS(O_ASYNC "sys/types.h;sys/fcntl.h" HAVE_OASYNC)
CHECK_SYMBOL_EXISTS(O_NOFOLLOW "sys/types.h;sys/fcntl.h" HAVE_ONOFOLLOW)
CHECK_SYMBOL_EXISTS(O_CLOEXEC "sys/types.h;sys/fcntl.h" HAVE_OCLOEXEC)
LIST(APPEND CMAKE_REQUIRED_INCLUDES "${LIBSSL_INCLUDE}")
CHECK_SYMBOL_EXISTS(SSL_set_tlsext_host_name "openssl/ssl.h" HAVE_SSL_TLSEXT_HOSTNAME)
CHECK_SYMBOL_EXISTS(dirfd "sys/types.h;unistd.h;dirent.h" HAVE_DIRFD)
CHECK_SYMBOL_EXISTS(fpathconf "sys/types.h;unistd.h" HAVE_FPATHCONF)
CHECK_SYMBOL_EXISTS(sigaltstack "signal.h" HAVE_SIGALTSTACK)
CHECK_SYMBOL_EXISTS(open_memstream "stdio.h" HAVE_OPENMEMSTREAM)
CHECK_SYMBOL_EXISTS(fmemopen "stdio.h" HAVE_FMEMOPEN)
CHECK_SYMBOL_EXISTS(clock_getcpuclockid "sys/types.h;time.h" HAVE_CLOCK_GETCPUCLOCKID)
CHECK_SYMBOL_EXISTS(RUSAGE_SELF "sys/types.h;sys/resource.h" HAVE_RUSAGE_SELF)

IF(ENABLE_PCRE2 MATCHES "ON")
	IF(HAVE_PCRE_JIT)
		SET(HAVE_PCRE_JIT_FAST 1)
	ENDIF()
ELSE()
	LIST(APPEND CMAKE_REQUIRED_INCLUDES "${PCRE_INCLUDE}")
	IF(PCRE_LIBRARY_PATH)
		SET(CMAKE_REQUIRED_LIBRARIES "${CMAKE_REQUIRED_LIBRARIES};-L${PCRE_LIBRARY_PATH};${PCRE_LIBRARY}")
	ELSE(PCRE_LIBRARY_PATH)
		SET(CMAKE_REQUIRED_LIBRARIES "${CMAKE_REQUIRED_LIBRARIES};-lpcre")
	ENDIF(PCRE_LIBRARY_PATH)
# Some PCRE implementations are lacking of pcre_jit_exec fast path
SET(_PCRE_FAST_TEST "
#include \"pcre.h\"
int main (void)
{
	int rc;
	int ovector[30];
	pcre *re;
	pcre_extra *extra;
	pcre_jit_stack *jit_stack;

	re = pcre_compile(\"abc\", 0, NULL, NULL, NULL);
	extra = pcre_study(re, PCRE_STUDY_JIT_COMPILE, NULL);
	jit_stack = pcre_jit_stack_alloc(32*1024, 512*1024);
	pcre_assign_jit_stack(extra, NULL, jit_stack);
	rc = pcre_jit_exec(re, extra, \"abc\", 3, 0, 0, ovector, 30, jit_stack);

	return rc;
}
")
CHECK_C_SOURCE_COMPILES("${_PCRE_FAST_TEST}" HAVE_PCRE_JIT_FAST)
IF(HAVE_PCRE_JIT_FAST)
	MESSAGE(STATUS "pcre_jit_exec is supported")
ELSE(HAVE_PCRE_JIT_FAST)
	MESSAGE(STATUS "pcre_jit_exec is -NOT- supported")
ENDIF(HAVE_PCRE_JIT_FAST)
ENDIF()

FILE(WRITE ${CMAKE_BINARY_DIR}/pthread_setpshared.c "
#include <pthread.h>
#include <stdlib.h>
int main (void)
{
	pthread_mutexattr_t mattr;
	if (pthread_mutexattr_init(&mattr) != 0) return 0;
	if (pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED) != 0) return 0;
	if (pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST) != 0) return 0;
	return 1;
}
")
TRY_RUN(_CAN_RUN _CAN_COMPILE
	"${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/pthread_setpshared.c"
	CMAKE_FLAGS CMAKE_C_FLAGS="-pthread")
IF(_CAN_RUN EQUAL 1)
	SET(HAVE_PTHREAD_PROCESS_SHARED 1 CACHE INTERNAL "")
	LIST(APPEND RSPAMD_REQUIRED_LIBRARIES "-lpthread")
ENDIF(_CAN_RUN EQUAL 1)
IF(HAVE_PTHREAD_PROCESS_SHARED)
	MESSAGE(STATUS "pthread_mutexattr_setpshared is supported")
ELSE(HAVE_PTHREAD_PROCESS_SHARED)
	MESSAGE(STATUS "pthread_mutexattr_setpshared is -NOT- supported")
ENDIF(HAVE_PTHREAD_PROCESS_SHARED)

IF(NOT HAVE_GETADDRINFO)
	MESSAGE(FATAL_ERROR "Your system does not support getaddrinfo call, please consider upgrading it to run rspamd")
ENDIF(NOT HAVE_GETADDRINFO)
IF(HAVE_SIGINFO_H)
	CHECK_SYMBOL_EXISTS(SA_SIGINFO "signal.h;siginfo.h" HAVE_SA_SIGINFO)
ELSE(HAVE_SIGINFO_H)
	CHECK_SYMBOL_EXISTS(SA_SIGINFO "signal.h" HAVE_SA_SIGINFO)
ENDIF(HAVE_SIGINFO_H)

IF(NOT CMAKE_SYSTEM_NAME STREQUAL "SunOS")
IF(HAVE_CLOCK_GETTIME)
	CHECK_SYMBOL_EXISTS(CLOCK_PROCESS_CPUTIME_ID time.h HAVE_CLOCK_PROCESS_CPUTIME_ID)
	CHECK_SYMBOL_EXISTS(CLOCK_VIRTUAL time.h HAVE_CLOCK_VIRTUAL)
ELSE(HAVE_CLOCK_GETTIME)
	CHECK_INCLUDE_FILES(sys/timeb.h HAVE_SYS_TIMEB_H)
ENDIF(HAVE_CLOCK_GETTIME)

# Check asm pause instruction
CHECK_C_SOURCE_COMPILES ("#include <sys/types.h>
						  int main (int argc, char **argv) {
							__asm __volatile(\"pause\");
							return 0;
						  }" HAVE_ASM_PAUSE)
ENDIF(NOT CMAKE_SYSTEM_NAME STREQUAL "SunOS")

CHECK_C_SOURCE_RUNS("
#include <stdbool.h>
int main(int argc, char **argv) {
        int a = 0, b = 0;
        if (__atomic_compare_exchange_n(&a, &b, 1, false, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) {
                return 0;
        }
        return -1;
}
" HAVE_ATOMIC_BUILTINS)

IF(NOT HAVE_ATOMIC_BUILTINS)
	MESSAGE(STATUS "atomic builtins are -NOT- supported")
ELSE()
	MESSAGE(STATUS "atomic builtins are supported")
ENDIF()

CHECK_C_SOURCE_RUNS("
#include <x86intrin.h>
int main(int argc, char **argv) {
        __builtin_ia32_lfence ();
        if (__builtin_ia32_rdtsc()) {
                return 0;
        }
        return -1;
}
" HAVE_RDTSC)

IF(NOT HAVE_RDTSC)
	MESSAGE(STATUS "rdtsc intrinsic is -NOT- supported")
ELSE()
	MESSAGE(STATUS "rdtsc intrinsic is supported")
ENDIF()

IF(CMAKE_SYSTEM_NAME STREQUAL "Linux")
	# In linux, we need to mount /run/shm to test which could be unavailable
	# on a build system. On the other hand, we know that linux has stupid
	# but compatible shmem support, so we assume this macro as true
	SET(HAVE_SANE_SHMEM 1)
ELSE()
	CHECK_C_SOURCE_RUNS("
	#include <sys/mman.h>
	#include <fcntl.h>
	#include <unistd.h>
	#define TEST_NAME \"/test-shmem-work\"
	int
	main (int argc, char **argv)
	{
	  int fd;

	  fd = shm_open (TEST_NAME, O_RDWR | O_CREAT | O_EXCL, 00600);
	  if (fd == -1) {
	    return -1;
	  }
	  if (ftruncate (fd, 100) == -1) {
	    shm_unlink (TEST_NAME);
	    close (fd);
	    return -1;
	  }

	  if (ftruncate (fd, 200) == -1) {
	    shm_unlink (TEST_NAME);
	    close (fd);
	    return -1;
	  }
	  if (ftruncate (fd, 300) == -1) {
	    shm_unlink (TEST_NAME);
	    close (fd);
	    return -1;
	  }

	  close (fd);
	  shm_unlink (TEST_NAME);
	  return 0;
	}
	" HAVE_SANE_SHMEM)
	IF(NOT HAVE_SANE_SHMEM)
		MESSAGE(STATUS "shmem support is NOT compatible with POSIX")
	ELSE()
		MESSAGE(STATUS "shmem support is compatible with POSIX")
	ENDIF()
ENDIF()

# Check queue.h compatibility
IF(NOT HAVE_COMPATIBLE_QUEUE_H)
	INCLUDE_DIRECTORIES(compat)
ENDIF(NOT HAVE_COMPATIBLE_QUEUE_H)

IF(ENABLE_URL_INCLUDE MATCHES "ON")
	FIND_LIBRARY(LIBFETCH_LIBRARY HINTS "${RSPAMD_SEARCH_PATH}"
					NAMES fetch PATHS	PATH_SUFFIXES lib64 lib
					PATHS ${RSPAMD_DEFAULT_LIBRARY_PATHS}
					DOC "Path where the libfetch library can be found")
	IF(LIBFETCH_LIBRARY)
		FIND_FILE(HAVE_FETCH_H HINTS "${RSPAMD_SEARCH_PATH}"
			NAMES fetch.h
			PATH_SUFFIXES include
			PATHS ${RSPAMD_DEFAULT_INCLUDE_PATHS}
					DOC "Path to libfetch header")
	ELSE(LIBFETCH_LIBRARY)
		# Try to find libcurl
		ProcessPackage(CURL LIBRARY curl INCLUDE curl.h INCLUDE_SUFFIXES include/curl
			ROOT ${CURL_ROOT})
		IF(NOT WITH_CURL)
			MESSAGE(WARNING "Neither libcurl nor libfetch were found, no support of URL includes in configuration")
		ENDIF(NOT WITH_CURL)
	ENDIF(LIBFETCH_LIBRARY)
ENDIF(ENABLE_URL_INCLUDE MATCHES "ON")

IF(NOT DESTDIR)
	SET(DESTDIR $ENV{DESTDIR})
ENDIF(NOT DESTDIR)


################################ SUBDIRS SECTION ###########################
ADD_SUBDIRECTORY(contrib/hiredis)
SET(WITH_HIREDIS 1)
INCLUDE_DIRECTORIES(BEFORE "${CMAKE_SOURCE_DIR}/contrib/hiredis")

LIST(APPEND RSPAMD_REQUIRED_LIBRARIES "${CMAKE_REQUIRED_LIBRARIES}")
IF(HAVE_FETCH_H)
	LIST(APPEND RSPAMD_REQUIRED_LIBRARIES fetch)
ENDIF(HAVE_FETCH_H)
IF(WITH_DB)
	LIST(APPEND RSPAMD_REQUIRED_LIBRARIES db)
ENDIF(WITH_DB)

LIST(APPEND RSPAMD_REQUIRED_LIBRARIES "${LUA_LIBRARY}")
LIST(APPEND RSPAMD_REQUIRED_LIBRARIES ucl)
LIST(APPEND RSPAMD_REQUIRED_LIBRARIES rdns)
LIST(APPEND RSPAMD_REQUIRED_LIBRARIES ottery)
LIST(APPEND RSPAMD_REQUIRED_LIBRARIES xxhash)

IF(GLIB_COMPAT)
	LIST(APPEND RSPAMD_REQUIRED_LIBRARIES glibadditions)
ENDIF(GLIB_COMPAT)


ADD_SUBDIRECTORY(contrib/xxhash)
ADD_SUBDIRECTORY(contrib/cdb)
ADD_SUBDIRECTORY(contrib/http-parser)
ADD_SUBDIRECTORY(contrib/fpconv)
ADD_SUBDIRECTORY(contrib/lc-btrie)
ADD_SUBDIRECTORY(contrib/libottery)
ADD_SUBDIRECTORY(contrib/zstd)
IF(ENABLE_SNOWBALL MATCHES "ON")
	ADD_SUBDIRECTORY(contrib/snowball)
	SET(WITH_SNOWBALL 1)
ENDIF()
ADD_SUBDIRECTORY(contrib/libucl)
ADD_SUBDIRECTORY(contrib/librdns)
ADD_SUBDIRECTORY(contrib/aho-corasick)
ADD_SUBDIRECTORY(contrib/lua-lpeg)
ADD_SUBDIRECTORY(contrib/t1ha)
ADD_SUBDIRECTORY(contrib/libev)
ADD_SUBDIRECTORY(contrib/kann)

IF (NOT WITH_LUAJIT)
	ADD_SUBDIRECTORY(contrib/lua-bit)
ENDIF()

IF (ENABLE_LUA_REPL MATCHES "ON")
	ADD_SUBDIRECTORY(contrib/replxx)
	SET(WITH_LUA_REPL 1)
	LIST(APPEND RSPAMD_REQUIRED_LIBRARIES rspamd-replxx)
ENDIF()

IF (ENABLE_SNOWBALL MATCHES "ON")
	LIST(APPEND RSPAMD_REQUIRED_LIBRARIES stemmer)
ENDIF()
LIST(APPEND RSPAMD_REQUIRED_LIBRARIES rspamd-hiredis)

LIST(APPEND RSPAMD_REQUIRED_LIBRARIES rspamd-actrie)
LIST(APPEND RSPAMD_REQUIRED_LIBRARIES rspamd-t1ha)
LIST(APPEND RSPAMD_REQUIRED_LIBRARIES rspamd-ev)
LIST(APPEND RSPAMD_REQUIRED_LIBRARIES rspamd-kann)

IF(ENABLE_CLANG_PLUGIN MATCHES "ON")
	ADD_SUBDIRECTORY(clang-plugin)
ENDIF()

ADD_SUBDIRECTORY(src)
ADD_SUBDIRECTORY(test)
ADD_SUBDIRECTORY(utils)

############################ TARGETS SECTION ###############################


CONFIGURE_FILE(config.h.in src/config.h)

##################### INSTALLATION ##########################################

# Binaries

# Configs
INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${CONFDIR})")
INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${SHAREDIR})")
INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${EXAMPLESDIR})")
INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${LUALIBDIR})")
INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${PLUGINSDIR})")
INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${RULESDIR})")

# Install configs only if they are unchanged
LIST(LENGTH CONFFILES CONFLIST_COUNT)
MATH(EXPR CONFLIST_MAX ${CONFLIST_COUNT}-1)

FILE(GLOB_RECURSE CONF_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/conf"
	"${CMAKE_CURRENT_SOURCE_DIR}/conf/*" )
FOREACH(CONF_FILE ${CONF_FILES})
	GET_FILENAME_COMPONENT(_rp ${CONF_FILE} PATH)
	INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${CONFDIR}/${_rp})")
	INSTALL(FILES "${CMAKE_CURRENT_SOURCE_DIR}/conf/${CONF_FILE}"
		DESTINATION ${CONFDIR}/${_rp})
ENDFOREACH(CONF_FILE)

SET(MAIN_CONF "conf/rspamd.conf")
IF(BUILD_PORT)
	INSTALL_IF_NOT_EXISTS(${MAIN_CONF} ${CONFDIR} "rspamd.conf" ".sample")
ELSE(BUILD_PORT)
	INSTALL_IF_NOT_EXISTS(${MAIN_CONF} ${CONFDIR} "rspamd.conf" "")
ENDIF(BUILD_PORT)
IF(INSTALL_EXAMPLES MATCHES "ON")
	INSTALL(FILES ${MAIN_CONF} DESTINATION ${EXAMPLESDIR})
ENDIF(INSTALL_EXAMPLES MATCHES "ON")

# Lua plugins

FILE(GLOB LUA_PLUGINS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/src/plugins/lua"
	"${CMAKE_CURRENT_SOURCE_DIR}/src/plugins/lua/*.lua" )
FOREACH(LUA_PLUGIN ${LUA_PLUGINS})
	GET_FILENAME_COMPONENT(_rp ${LUA_PLUGIN} PATH)
	INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${PLUGINSDIR}/${_rp})")
	INSTALL(FILES "src/plugins/lua/${LUA_PLUGIN}" DESTINATION ${PLUGINSDIR}/${_rp})
ENDFOREACH(LUA_PLUGIN)


# Install TLD list
INSTALL(FILES "contrib/publicsuffix/effective_tld_names.dat" DESTINATION
	"${SHAREDIR}")

# Install languages data
INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${SHAREDIR}/languages)")
FILE(GLOB LANGUAGES "${CMAKE_CURRENT_SOURCE_DIR}/contrib/languages-data/*.json")
FOREACH(_LANG ${LANGUAGES})
	INSTALL(FILES "${_LANG}" DESTINATION ${SHAREDIR}/languages)
ENDFOREACH()
INSTALL(FILES "${CMAKE_CURRENT_SOURCE_DIR}/contrib/languages-data/stop_words" DESTINATION ${SHAREDIR}/languages)

# Lua config
FILE(GLOB_RECURSE LUA_CONFIGS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/rules"
	"${CMAKE_CURRENT_SOURCE_DIR}/rules/*.lua")
FOREACH(LUA_CONF ${LUA_CONFIGS})
	GET_FILENAME_COMPONENT(_rp ${LUA_CONF} PATH)
	INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${RULESDIR}/${_rp})")
	INSTALL(FILES "rules/${LUA_CONF}" DESTINATION ${RULESDIR}/${_rp})
ENDFOREACH(LUA_CONF)

# Lua libs
FILE(GLOB_RECURSE LUA_LIBS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/lualib"
		"${CMAKE_CURRENT_SOURCE_DIR}/lualib/*.lua")
FOREACH(LUA_LIB ${LUA_LIBS})
	GET_FILENAME_COMPONENT(_rp ${LUA_LIB} PATH)
	INSTALL(CODE "FILE(MAKE_DIRECTORY \$ENV{DESTDIR}${LUALIBDIR}/${_rp})")
	INSTALL(FILES "lualib/${LUA_LIB}" DESTINATION ${LUALIBDIR}/${_rp})
ENDFOREACH(LUA_LIB)

# Install lua fun library
INSTALL(FILES "contrib/lua-fun/fun.lua" DESTINATION ${LUALIBDIR})
INSTALL(FILES "contrib/lua-argparse/argparse.lua" DESTINATION ${LUALIBDIR})
INSTALL(FILES "contrib/lua-tableshape/tableshape.lua" DESTINATION ${LUALIBDIR})
INSTALL(FILES "contrib/lua-lupa/lupa.lua" DESTINATION ${LUALIBDIR})
INSTALL(FILES "contrib/lua-lpeg/lpegre.lua" DESTINATION ${LUALIBDIR})

# systemd unit
IF(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND WANT_SYSTEMD_UNITS MATCHES "ON")
	INSTALL(FILES "rspamd.service" DESTINATION ${SYSTEMDDIR})
ENDIF(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND WANT_SYSTEMD_UNITS MATCHES "ON")

# Manual pages
INSTALL(FILES "doc/rspamd.8" DESTINATION ${MANDIR}/man8)
INSTALL(FILES "doc/rspamc.1" DESTINATION ${MANDIR}/man1)
INSTALL(FILES "doc/rspamadm.1" DESTINATION ${MANDIR}/man1)

# Utils
INSTALL(PROGRAMS "utils/rspamd_stats.pl" RENAME rspamd_stats DESTINATION bin)

# Install webui
IF(INSTALL_WEBUI MATCHES "ON")
	INSTALL(DIRECTORY "interface/" DESTINATION ${WWWDIR} PATTERN ".git" EXCLUDE)
ENDIF(INSTALL_WEBUI MATCHES "ON")


INSTALL(DIRECTORY "contrib/elastic/" DESTINATION "${SHAREDIR}/elastic" PATTERN ".git" EXCLUDE)

ADD_CUSTOM_TARGET(dist ${CMAKE_SOURCE_DIR}/dist.sh
	"${CMAKE_BINARY_DIR}/rspamd-${RSPAMD_VERSION}.tar.xz" "${TAR}"
	COMMENT "Create source distribution"
	WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})

IF(NOT DEBIAN_BUILD)
	ADD_CUSTOM_TARGET(check DEPENDS rspamd-test)
	ADD_CUSTOM_TARGET(run-test DEPENDS check COMMAND test/rspamd-test)
ENDIF(NOT DEBIAN_BUILD)


# PVS Studio
find_program(_PVS_STUDIO "pvs-studio-analyzer")

if(_PVS_STUDIO)
	include(${CMAKE_SOURCE_DIR}/PVS-Studio.cmake)
	pvs_studio_add_target(TARGET ${PROJECT_NAME}.analyze
			ANALYZE ${PROJECT_NAME} rspamd-server rspamadm rspamc
			OUTPUT FORMAT errorfile
			LOG target_${PROJECT_NAME}.err)
endif()