aboutsummaryrefslogtreecommitdiff
blob: f449220040763ac9f97f6cc66bc14707b2cde743 (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
# Copyright 1999-2013 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $

# @ECLASS: cmake-utils.eclass
# @MAINTAINER:
# kde@gentoo.org
# @AUTHOR:
# Tomáš Chvátal <scarabeus@gentoo.org>
# Maciej Mrozowski <reavertm@gentoo.org>
# (undisclosed contributors)
# Original author: Zephyrus (zephyrus@mirach.it)
# @BLURB: common ebuild functions for cmake-based packages
# @DESCRIPTION:
# The cmake-utils eclass makes creating ebuilds for cmake-based packages much easier.
# It provides all inherited features (DOCS, HTML_DOCS, PATCHES) along with out-of-source
# builds (default), in-source builds and an implementation of the well-known use_enable
# and use_with functions for CMake.

if [[ ${___ECLASS_ONCE_CMAKE_UTILS} != "recur -_+^+_- spank" ]] ; then
___ECLASS_ONCE_CMAKE_UTILS="recur -_+^+_- spank"

# @ECLASS-VARIABLE: WANT_CMAKE
# @DESCRIPTION:
# Specify if cmake-utils eclass should depend on cmake optionally or not.
# This is usefull when only part of aplication is using cmake build system.
# Valid values are: always [default], optional (where the value is the useflag
# used for optionality)
WANT_CMAKE="${WANT_CMAKE:-always}"

# @ECLASS-VARIABLE: CMAKE_MIN_VERSION
# @DESCRIPTION:
# Specify the minimum required CMake version.
CMAKE_MIN_VERSION="${CMAKE_MIN_VERSION:-2.8.9}"

# @ECLASS-VARIABLE: CMAKE_REMOVE_MODULES_LIST
# @DESCRIPTION:
# Space-separated list of CMake modules that will be removed in $S during src_prepare,
# in order to force packages to use the system version.
CMAKE_REMOVE_MODULES_LIST="${CMAKE_REMOVE_MODULES_LIST:-FindBLAS FindLAPACK}"

# @ECLASS-VARIABLE: CMAKE_REMOVE_MODULES
# @DESCRIPTION:
# Do we want to remove anything? yes or whatever else for no
CMAKE_REMOVE_MODULES="${CMAKE_REMOVE_MODULES:-yes}"

# @ECLASS-VARIABLE: CMAKE_MAKEFILE_GENERATOR
# @DESCRIPTION:
# Specify a makefile generator to be used by cmake.
# At this point only "emake" and "ninja" are supported.
CMAKE_MAKEFILE_GENERATOR="${CMAKE_MAKEFILE_GENERATOR:-emake}"

# @ECLASS-VARIABLE: CMAKE_WARN_UNUSED_CLI
# @DESCRIPTION:
# Warn about variables that are declared on the command line
# but not used. Might give false-positives.
# "no" to disable (default) or anything else to enable.
CMAKE_WARN_UNUSED_CLI="${CMAKE_WARN_UNUSED_CLI:-no}"

CMAKEDEPEND=""
case ${WANT_CMAKE} in
	always)
		;;
	*)
		IUSE+=" ${WANT_CMAKE}"
		CMAKEDEPEND+="${WANT_CMAKE}? ( "
		;;
esac
inherit my-god-its-full-of-quotation-marks ehooker toolchain-funcs multilib flag-o-matic eutils

CMAKE_EXPF="src_compile src_test src_install"
case ${EAPI:-0} in
	2|3|4|5) CMAKE_EXPF+=" src_prepare src_configure" ;;
	1|0) eerror "cmake-utils no longer supports EAPI 0-1." && die
	;;
	*) die "Unknown EAPI, bug eclass maintainers." ;;
esac
EXPORT_FUNCTIONS ${CMAKE_EXPF}

case ${CMAKE_MAKEFILE_GENERATOR} in
	emake)
		CMAKEDEPEND+=" sys-devel/make"
		;;
	ninja)
		CMAKEDEPEND+=" dev-util/ninja"
		;;
	*)
		eerror "Unknown value for \${CMAKE_MAKEFILE_GENERATOR}"
		die "Value ${CMAKE_MAKEFILE_GENERATOR} is not supported"
		;;
esac

if [[ ${PN} != cmake ]]; then
	CMAKEDEPEND+=" >=dev-util/cmake-${CMAKE_MIN_VERSION}"
fi

CMAKEDEPEND+=" userland_GNU? ( >=sys-apps/findutils-4.4.0 )"

[[ ${WANT_CMAKE} = always ]] || CMAKEDEPEND+=" )"

DEPEND="${CMAKEDEPEND}"
unset CMAKEDEPEND

# Internal functions used by cmake-utils_use_*
_use_me_now() {
	debug-print-function ${FUNCNAME} "$@"

	local uper capitalised x
	[[ -z $2 ]] && die "cmake-utils_use-$1 <USE flag> [<flag name>]"
	if [[ ! -z $3 ]]; then
		# user specified the use name so use it
		echo "-D$1$3=$(use $2 && echo ON || echo OFF)"
	else
		# use all various most used combinations
		uper=$(echo ${2} | tr '[:lower:]' '[:upper:]')
		capitalised=$(echo ${2} | sed 's/\<\(.\)\([^ ]*\)/\u\1\L\2/g')
		for x in $2 $uper $capitalised; do
			echo "-D$1$x=$(use $2 && echo ON || echo OFF) "
		done
	fi
}
_use_me_now_inverted() {
	debug-print-function ${FUNCNAME} "$@"

	local uper capitalised x
	[[ -z $2 ]] && die "cmake-utils_use-$1 <USE flag> [<flag name>]"
	if [[ ! -z $3 ]]; then
		# user specified the use name so use it
		echo "-D$1$3=$(use $2 && echo OFF || echo ON)"
	else
		# use all various most used combinations
		uper=$(echo ${2} | tr '[:lower:]' '[:upper:]')
		capitalised=$(echo ${2} | sed 's/\<\(.\)\([^ ]*\)/\u\1\L\2/g')
		for x in $2 $uper $capitalised; do
			echo "-D$1$x=$(use $2 && echo OFF || echo ON) "
		done
	fi
}

# @ECLASS-VARIABLE: BUILD_DIR
# @DESCRIPTION:
# Build directory where all cmake processed files should be generated.
# For in-source build it's fixed to ${CMAKE_USE_DIR}.
# For out-of-source build it can be overriden, by default it uses
# ${WORKDIR}/${P}_build.
#
# This variable has been called CMAKE_BUILD_DIR formerly.
# It is set under that name for compatibility.

# @ECLASS-VARIABLE: CMAKE_BUILD_TYPE
# @DESCRIPTION:
# Set to override default CMAKE_BUILD_TYPE. Only useful for packages
# known to make use of "if (CMAKE_BUILD_TYPE MATCHES xxx)".
# If about to be set - needs to be set before invoking cmake-utils_src_configure.
# You usualy do *NOT* want nor need to set it as it pulls CMake default build-type
# specific compiler flags overriding make.conf.
: ${CMAKE_BUILD_TYPE:=Gentoo}

# @ECLASS-VARIABLE: CMAKE_IN_SOURCE_BUILD
# @DESCRIPTION:
# Set to enable in-source build.

# @ECLASS-VARIABLE: CMAKE_USE_DIR
# @DESCRIPTION:
# Sets the directory where we are working with cmake.
# For example when application uses autotools and only one
# plugin needs to be done by cmake.
# By default it uses ${S}.

# @ECLASS-VARIABLE: CMAKE_VERBOSE
# @DESCRIPTION:
# Set to OFF to disable verbose messages during compilation
: ${CMAKE_VERBOSE:=ON}

# @ECLASS-VARIABLE: PREFIX
# @DESCRIPTION:
# Eclass respects PREFIX variable, though it's not recommended way to set
# install/lib/bin prefixes.
# Use -DCMAKE_INSTALL_PREFIX=... CMake variable instead.
: ${PREFIX:=/usr}

# @ECLASS-VARIABLE: CMAKE_BINARY
# @DESCRIPTION:
# Eclass can use different cmake binary than the one provided in by system.
: ${CMAKE_BINARY:=cmake}

# Determine using IN or OUT source build
_check_build_dir() {
	: ${CMAKE_USE_DIR:=${S}}
	if [[ -n ${CMAKE_IN_SOURCE_BUILD} ]]; then
		# we build in source dir
		BUILD_DIR="${CMAKE_USE_DIR}"
	else
		# Respect both the old variable and the new one, depending
		# on which one was set by the ebuild.
		if [[ ! ${BUILD_DIR} && ${CMAKE_BUILD_DIR} ]]; then
			eqawarn "The CMAKE_BUILD_DIR variable has been renamed to BUILD_DIR."
			eqawarn "Please migrate the ebuild to use the new one."

			# In the next call, both variables will be set already
			# and we'd have to know which one takes precedence.
			_RESPECT_CMAKE_BUILD_DIR=1
		fi

		if [[ ${_RESPECT_CMAKE_BUILD_DIR} ]]; then
			BUILD_DIR=${CMAKE_BUILD_DIR:-${WORKDIR}/${P}_build}
		else
			: ${BUILD_DIR:=${WORKDIR}/${P}_build}
		fi
	fi

	# Backwards compatibility for getting the value.
	CMAKE_BUILD_DIR=${BUILD_DIR}

	mkdir -p "${BUILD_DIR}"
	echo ">>> Working in BUILD_DIR: \"$BUILD_DIR\""
}

# Determine which generator to use
_generator_to_use() {
	local generator_name

	case ${CMAKE_MAKEFILE_GENERATOR} in
		ninja)
			generator_name="Ninja"
			;;
		emake)
			generator_name="Unix Makefiles"
			;;
		*)
			eerror "Unknown value for \${CMAKE_MAKEFILE_GENERATOR}"
			die "Value ${CMAKE_MAKEFILE_GENERATOR} is not supported"
			;;
	esac

	echo ${generator_name}
}

# @FUNCTION: cmake-utils_use_with
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on use_with. See ebuild(5).
#
# `cmake-utils_use_with foo FOO` echoes -DWITH_FOO=ON if foo is enabled
# and -DWITH_FOO=OFF if it is disabled.
cmake-utils_use_with() { _use_me_now WITH_ "$@" ; }

# @FUNCTION: cmake-utils_use_enable
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on use_enable. See ebuild(5).
#
# `cmake-utils_use_enable foo FOO` echoes -DENABLE_FOO=ON if foo is enabled
# and -DENABLE_FOO=OFF if it is disabled.
cmake-utils_use_enable() { _use_me_now ENABLE_ "$@" ; }

# @FUNCTION: cmake-utils_use_find_package
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on use_enable. See ebuild(5).
#
# `cmake-utils_use_find_package foo LibFoo` echoes -DCMAKE_DISABLE_FIND_PACKAGE_LibFoo=OFF
# if foo is enabled and -DCMAKE_DISABLE_FIND_PACKAGE_LibFoo=ON if it is disabled.
# This can be used to make find_package optional (since cmake-2.8.6).
cmake-utils_use_find_package() { _use_me_now_inverted CMAKE_DISABLE_FIND_PACKAGE_ "$@" ; }

# @FUNCTION: cmake-utils_use_disable
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on inversion of use_enable. See ebuild(5).
#
# `cmake-utils_use_enable foo FOO` echoes -DDISABLE_FOO=OFF if foo is enabled
# and -DDISABLE_FOO=ON if it is disabled.
cmake-utils_use_disable() { _use_me_now_inverted DISABLE_ "$@" ; }

# @FUNCTION: cmake-utils_use_no
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on use_disable. See ebuild(5).
#
# `cmake-utils_use_no foo FOO` echoes -DNO_FOO=OFF if foo is enabled
# and -DNO_FOO=ON if it is disabled.
cmake-utils_use_no() { _use_me_now_inverted NO_ "$@" ; }

# @FUNCTION: cmake-utils_use_want
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on use_enable. See ebuild(5).
#
# `cmake-utils_use_want foo FOO` echoes -DWANT_FOO=ON if foo is enabled
# and -DWANT_FOO=OFF if it is disabled.
cmake-utils_use_want() { _use_me_now WANT_ "$@" ; }

# @FUNCTION: cmake-utils_use_build
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on use_enable. See ebuild(5).
#
# `cmake-utils_use_build foo FOO` echoes -DBUILD_FOO=ON if foo is enabled
# and -DBUILD_FOO=OFF if it is disabled.
cmake-utils_use_build() { _use_me_now BUILD_ "$@" ; }

# @FUNCTION: cmake-utils_use_has
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on use_enable. See ebuild(5).
#
# `cmake-utils_use_has foo FOO` echoes -DHAVE_FOO=ON if foo is enabled
# and -DHAVE_FOO=OFF if it is disabled.
cmake-utils_use_has() { _use_me_now HAVE_ "$@" ; }

# @FUNCTION: cmake-utils_use_use
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on use_enable. See ebuild(5).
#
# `cmake-utils_use_use foo FOO` echoes -DUSE_FOO=ON if foo is enabled
# and -DUSE_FOO=OFF if it is disabled.
cmake-utils_use_use() { _use_me_now USE_ "$@" ; }

# @FUNCTION: cmake-utils_use
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on use_enable. See ebuild(5).
#
# `cmake-utils_use foo FOO` echoes -DFOO=ON if foo is enabled
# and -DFOO=OFF if it is disabled.
cmake-utils_use() { _use_me_now "" "$@" ; }

# @FUNCTION: cmake-utils_useno
# @USAGE: <USE flag> [flag name]
# @DESCRIPTION:
# Based on use_enable. See ebuild(5).
#
# `cmake-utils_useno foo NOFOO` echoes -DNOFOO=OFF if foo is enabled
# and -DNOFOO=ON if it is disabled.
cmake-utils_useno() { _use_me_now_inverted "" "$@" ; }

# Internal function for modifying hardcoded definitions.
# Removes dangerous definitions that override Gentoo settings.
_modify-cmakelists() {
	debug-print-function ${FUNCNAME} "$@"

	# Only edit the files once
	grep -qs "<<< Gentoo configuration >>>" "${CMAKE_USE_DIR}"/CMakeLists.txt && return 0

	# Comment out all set (<some_should_be_user_defined_variable> value)
	# TODO Add QA checker - inform when variable being checked for below is set in CMakeLists.txt
	find "${CMAKE_USE_DIR}" -name CMakeLists.txt \
		-exec sed -i -e '/^[[:space:]]*[sS][eE][tT][[:space:]]*([[:space:]]*CMAKE_BUILD_TYPE.*)/{s/^/#IGNORE /g}' {} + \
		-exec sed -i -e '/^[[:space:]]*[sS][eE][tT][[:space:]]*([[:space:]]*CMAKE_COLOR_MAKEFILE.*)/{s/^/#IGNORE /g}' {} + \
		-exec sed -i -e '/^[[:space:]]*[sS][eE][tT][[:space:]]*([[:space:]]*CMAKE_INSTALL_PREFIX.*)/{s/^/#IGNORE /g}' {} + \
		-exec sed -i -e '/^[[:space:]]*[sS][eE][tT][[:space:]]*([[:space:]]*CMAKE_VERBOSE_MAKEFILE.*)/{s/^/#IGNORE /g}' {} + \
		|| die "${LINENO}: failed to disable hardcoded settings"

	# NOTE Append some useful summary here
	cat >> "${CMAKE_USE_DIR}"/CMakeLists.txt <<- _EOF_

		MESSAGE(STATUS "<<< Gentoo configuration >>>
		Build type      \${CMAKE_BUILD_TYPE}
		Install path    \${CMAKE_INSTALL_PREFIX}
		Compiler flags:
		C               \${CMAKE_C_FLAGS}
		C++             \${CMAKE_CXX_FLAGS}
		Linker flags:
		Executable      \${CMAKE_EXE_LINKER_FLAGS}
		Module          \${CMAKE_MODULE_LINKER_FLAGS}
		Shared          \${CMAKE_SHARED_LINKER_FLAGS}\n")
	_EOF_
}

enable_cmake-utils_src_prepare() {
	debug-print-function ${FUNCNAME} "$@"

	debug-print "$FUNCNAME: PATCHES=$PATCHES"
	declare -a PATCHES=("${PATCHES[@]}")

	pushd "${S}" > /dev/null
	if ehook_fire cmake-utils-pre_src_prepare ; then
		[[ ${PATCHES[@]} ]] && epatch "${PATCHES[@]}"
		debug-print "$FUNCNAME: applying user patches"
		epatch_user
	fi
	ehook_fire cmake-utils-post_src_prepare -u
	popd > /dev/null
}

# retrieve a variable (i.e.: FOO) using i.e.: tc_getFOO,
# unless the variable is already defined to a nonempty value,
# in which case, it is returned unaltered
_cmake-utils_tc_get_if_needed() {
	local v="$1" s
	if [[ ${!v} ]] ; then
		s="${!v}"
	else
		s=$(tc-get${v})
	fi
	echo "${s}"
}

# trim the preceeding and trailing whitespace from a string,
# leaving inner spaces intact
_cmake-utils_trimmed() {
	local s="$*"
	while [[ ${s:0:1} =~ [[:space:]] ]] ; do
		s="${s:1}"
	done
	while [[ ${s:$((${#s}-1))} =~ [[:space:]] ]] ; do
		s="${s:0:$((${#s}-1))}"
	done
	echo "${s}"
}

# given a string, retrieve the first word (consisting of non-space characters)
# after trimming any leading whitespace.
_cmake-utils_first_word_of() {
	local s=$(_cmake-utils_trimmed "$*")
	echo "${s%% *}"
}

# given a string, retrieve the rest of the string after the first word,
# with any whitespace trimmed, retaining any whitespace between words
# (except whitespace that was between the first and second word)
_cmake-utils_subsequent_words_of() {
	local s=$(_cmake-utils_trimmed "$*")
	if [[ ${s} ]] ; then
		s="${s#$(_cmake-utils_first_word_of "${s}")}"
		echo "$(_cmake-utils_trimmed "${s}")"
	else
		echo ""
	fi
}

# given a variable-name, retrieve it with _cmake-utils_tc_get_if_needed
# and then from that retreive the first word
_cmake-utils_get_first_word() {
	local s=$(_cmake-utils_tc_get_if_needed "$1")
	echo "$(_cmake-utils_first_word_of "${s}")"
}

# given a command-containing variable as the first argument,
# uses _cmake-utils_tc_get_if_needed to retrieve the var, and then
# returns type -P of the first word of it, ignoring rest.
_cmake-utils_get_first_word_executable() {
	local w=$(_cmake-utils_get_first_word "$1")
	if [[ ${w} ]] ; then
		echo "$(type -P "${w}")"
	else
		echo ""
	fi
}

# fetches any additional bits of a variable not included in
# _cmake-utils_get_first_word.  takes the variable name as an input.
# May return an empty string.
_cmake-utils_get_subsequent_words() {
	local s=$(_cmake-utils_tc_get_if_needed "$1")
	echo "$(_cmake-utils_subsequent_words_of "${s}")"
}

# @FUNCTION: _cmake-utils_do_with_unset_vars
# @USAGE: <string-list of variable-names> <command> [<args> ...]
# @INTERNAL
# @DESCRIPTION:
# Runs the command "<command> <args> ..." with all the variables in the
# provided list unset and unexported, while minimizing side-effects
_cmake-utils_do_with_unset_vars() {
	debug-print-function ${FUNCNAME} "$@"

	[[ $# -lt 2 ]] && die "${FUNCNAME}: requires at least two arguments"
	local vars="$1" var
	shift
	for var in ${vars} ; do
		# this nonsense is AFAIK the only way to un-set and un-export
		# "${var}" without screwing up values of var in calling functions,
		# and without subshells.  Why does it work?  What is the fundamental
		# principle of scoping in bash that we here exploit?  Excellent question!
		# No clue here though, it's just a magic incantation to me. -gmt
		local "${var}"
		unset "${var}"
	done
	unset var
	unset vars
	"$@"
}

# @VARIABLE: mycmakeargs
# @DEFAULT_UNSET
# @DESCRIPTION:
# Optional cmake defines as a bash array. Should be defined before calling
# src_configure.
# @CODE
# src_configure() {
# 	local mycmakeargs=(
# 		$(cmake-utils_use_with openconnect)
# 	)
# 	cmake-utils_src_configure
# }

enable_cmake-utils_src_configure() {
	debug-print-function ${FUNCNAME} "$@"

	# FIXME: not multi-ABI safe
	[[ "${CMAKE_REMOVE_MODULES}" == "yes" ]] && {
		local name
		for name in ${CMAKE_REMOVE_MODULES_LIST} ; do
			find "${S}" -name ${name}.cmake -exec rm -v {} +
		done
	}

	_check_build_dir

	# check if CMakeLists.txt exist and if no then die
	if [[ ! -e ${CMAKE_USE_DIR}/CMakeLists.txt ]] ; then
		eerror "Unable to locate CMakeLists.txt under:"
		eerror "\"${CMAKE_USE_DIR}/CMakeLists.txt\""
		eerror "Consider not inheriting the cmake eclass."
		die "FATAL: Unable to find CMakeLists.txt"
	fi

	# Remove dangerous things.
	_modify-cmakelists

	# Fix xdg collision with sandbox
	export XDG_CONFIG_HOME="${T}"

	# @SEE CMAKE_BUILD_TYPE
	if [[ ${CMAKE_BUILD_TYPE} = Gentoo ]]; then
		# Handle release builds
		if ! has debug ${IUSE//+} || ! use debug; then
			append-cppflags -DNDEBUG
		fi
	fi

	# Prepare Gentoo override rules (set valid compiler, append CPPFLAGS etc.)
	local build_rules=${BUILD_DIR}/gentoo_rules.cmake

	local _CMAKE_C_COMPILER=$(_cmake-utils_get_first_word_executable CC)
	local _CCORPHANS=$(_cmake-utils_get_subsequent_words CC)
	local _CMAKE_C_COMPILER_ARG1_COMMAND=
	local _CMAKE_CXX_COMPILER=$(_cmake-utils_get_first_word_executable CXX)
	local _CXXORPHANS=$(_cmake-utils_get_subsequent_words CXX)
	local _CMAKE_CXX_COMPILER_ARG1_COMMAND=

	# This seems fairly rediculous to me, but if C{,XX}ORPHANS is nonempty, then, in order to prevent
	# duplication of the first argument, we must handle the first word specially
	if [[ ${_CCORPHANS} ]] ; then
		_CMAKE_C_COMPILER_ARG1_COMMAND="SET (CMAKE_C_COMPILER_ARG1 $(_cmake-utils_first_word_of "${_CCORPHANS}") CACHE STRING \"C compiler first argument\" FORCE)"
		_CCORPHANS=$(_cmake-utils_subsequent_words_of "${_CCORPHANS}")
	fi
	if [[ ${_CXXORPHANS} ]] ; then
		_CMAKE_CXX_COMPILER_ARG1_COMMAND="SET (CMAKE_CXX_COMPILER_ARG1 $(_cmake-utils_first_word_of "${_CXXORPHANS}") CACHE STRING \"C++ compiler first argument\" FORCE)"
		_CXXORPHANS=$(_cmake-utils_subsequent_words_of "${_CXXORPHANS}")
	fi

	cat > "${build_rules}" <<- _EOF_
		SET (CMAKE_C_COMPILER "${_CMAKE_C_COMPILER}" CACHE FILEPATH "C compiler" FORCE)
		${_CMAKE_C_COMPILER_ARG1_COMMAND}
		SET (CMAKE_CXX_COMPILER "${_CMAKE_CXX_COMPILER}" CACHE FILEPATH "C++ compiler" FORCE)
		${_CMAKE_CXX_COMPILER_ARG1_COMMAND}
		SET (CMAKE_AR "$(_cmake-utils_get_first_word_executable AR)" CACHE FILEPATH "Archive manager" FORCE)
		SET (CMAKE_RANLIB "$(_cmake-utils_get_first_word_executable RANLIB)" CACHE FILEPATH "Archive index generator" FORCE)
		SET (CMAKE_ASM_COMPILE_OBJECT "<CMAKE_C_COMPILER> ${_CCORPHANS}${_CCORPHANS:+ }<DEFINES> ${CFLAGS}${CFLAGS:+ }<FLAGS> -o <OBJECT> -c <SOURCE>" CACHE STRING "ASM compile command" FORCE)
		SET (CMAKE_C_COMPILE_OBJECT "<CMAKE_C_COMPILER> ${_CCORPHANS}${_CCORPHANS:+ }<DEFINES> ${CFLAGS}${CFLAGS:+ }<FLAGS> -o <OBJECT> -c <SOURCE>" CACHE STRING "C compile command" FORCE)
		SET (CMAKE_CXX_COMPILE_OBJECT "<CMAKE_CXX_COMPILER> ${_CXXORPHANS}${_CXXORPHANS:+ }<DEFINES> ${CXXFLAGS}${CXXFLAGS:+ }<FLAGS> -o <OBJECT> -c <SOURCE>" CACHE STRING "C++ compile command" FORCE)
		SET (CMAKE_C_LINK_EXECUTABLE "<CMAKE_C_COMPILER> ${_CCORPHANS}${_CCORPHANS:+ }<FLAGS> ${LDFLAGS}${LDFLAGS:+ }<CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>" CACHE STRING "C link command for executables" FORCE)
		SET (CMAKE_C_CREATE_SHARED_LIBRARY "<CMAKE_C_COMPILER> ${_CCORPHANS}${_CCORPHANS:+ }<CMAKE_SHARED_LIBRARY_C_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> ${LDFLAGS}${LDFLAGS:+ }<CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_C_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" CACHE STRING "C shared library link command" FORCE)
		SET (CMAKE_C_CREATE_SHARED_MODULE "\${CMAKE_C_CREATE_SHARED_LIBRARY}" CACHE STRING "C shared module link command" FORCE)
		SET (CMAKE_CXX_LINK_EXECUTABLE "<CMAKE_CXX_COMPILER> ${_CXXORPHANS}${_CXXORPHANS:+ }<FLAGS> ${LDFLAGS}${LDFLAGS:+ }<CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>" CACHE STRING "C++ link command for executables" FORCE)
		SET (CMAKE_CXX_CREATE_SHARED_LIBRARY "<CMAKE_CXX_COMPILER> ${_CXXORPHANS}${_CXXORPHANS:+ }<CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> ${LDFLAGS}${LDFLAGS:+ }<CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" CACHE STRING "C++ shared library link command" FORCE)
		SET (CMAKE_CXX_CREATE_SHARED_MODULE "\${CMAKE_CXX_CREATE_SHARED_LIBRARY}" CACHE STRING "C++ shared module link command" FORCE)
		SET (PKG_CONFIG_EXECUTABLE "$(_cmake-utils_get_first_word_executable PKG_CONFIG)" CACHE FILEPATH "pkg-config executable" FORCE)
	_EOF_

	unset _CMAKE_C_COMPILER _CMAKE_CXX_COMPILER _CCORPHANS _CXXORPHANS _CMAKE_C_COMPILER_ARG1_COMMAND _CMAKE_CXX_COMPILER_ARG1_COMMAND

	has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX=

	if [[ ${EPREFIX} ]]; then
		cat >> "${build_rules}" <<- _EOF_
			# in Prefix we need rpath and must ensure cmake gets our default linker path
			# right ... except for Darwin hosts
			IF (NOT APPLE)
			SET (CMAKE_SKIP_RPATH OFF CACHE BOOL "" FORCE)
			SET (CMAKE_PLATFORM_REQUIRED_RUNTIME_PATH "${EPREFIX}/usr/${CHOST}/lib/gcc;${EPREFIX}/usr/${CHOST}/lib;${EPREFIX}/usr/$(get_libdir);${EPREFIX}/$(get_libdir)"
			CACHE STRING "" FORCE)

			ELSE ()

			SET(CMAKE_PREFIX_PATH "${EPREFIX}${PREFIX}" CACHE STRING "" FORCE)
			SET(CMAKE_SKIP_BUILD_RPATH OFF CACHE BOOL "" FORCE)
			SET(CMAKE_SKIP_RPATH OFF CACHE BOOL "" FORCE)
			SET(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE CACHE BOOL "")
			SET(CMAKE_INSTALL_RPATH "${EPREFIX}${PREFIX}/lib;${EPREFIX}/usr/${CHOST}/lib/gcc;${EPREFIX}/usr/${CHOST}/lib;${EPREFIX}/usr/$(get_libdir);${EPREFIX}/$(get_libdir)" CACHE STRING "" FORCE)
			SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE CACHE BOOL "" FORCE)
			SET(CMAKE_INSTALL_NAME_DIR "${EPREFIX}${PREFIX}/lib" CACHE STRING "" FORCE)

			ENDIF (NOT APPLE)
		_EOF_
	fi

	# Common configure parameters (invariants)
	local common_config=${BUILD_DIR}/gentoo_common_config.cmake
	local libdir=$(get_libdir)
	cat > "${common_config}" <<- _EOF_
		SET (LIB_SUFFIX ${libdir/lib} CACHE STRING "library path suffix" FORCE)
		SET (CMAKE_INSTALL_LIBDIR ${libdir} CACHE PATH "Output directory for libraries")
	_EOF_
	[[ "${NOCOLOR}" = true || "${NOCOLOR}" = yes ]] && echo 'SET (CMAKE_COLOR_MAKEFILE OFF CACHE BOOL "pretty colors during make" FORCE)' >> "${common_config}"

	# For reasons I can't fathom (too new feature?) cmake does not at all respect
	# PKG_CONFIG_LIBDIR from the ebuild environment.  Shove it down cmakes' throat.
	# Note that there's no caching of environment variables such as this --
	# the variable dies at compile-time, but by then hopefully pkg-config has
	# worked it's magic and all is well in the universe.
	[[ -n ${PKG_CONFIG_LIBDIR} ]] && \
		echo "SET (ENV{PKG_CONFIG_LIBDIR} \"${PKG_CONFIG_LIBDIR}\")" >> ${common_config}
	[[ -n ${PKG_CONFIG_PATH} ]] && \
		echo "SET (ENV{PKG_CONFIG_PATH} \"${PKG_CONFIG_PATH}\")" >> ${common_config}

	# Convert mycmakeargs to an array, for backwards compatibility
	# Make the array a local variable since <=portage-2.1.6.x does not
	# support global arrays (see bug #297255).
	if [[ $(declare -p mycmakeargs 2>&-) != "declare -a mycmakeargs="* ]]; then
		declare -a mycmakeargs=(${mycmakeargs})
	else
		declare -a mycmakeargs=("${mycmakeargs[@]}")
	fi

	if [[ ${CMAKE_WARN_UNUSED_CLI} == no ]] ; then
		local warn_unused_cli="--no-warn-unused-cli"
	else
		local warn_unused_cli=""
	fi

	# Common configure parameters (overridable)
	# NOTE CMAKE_BUILD_TYPE can be only overriden via CMAKE_BUILD_TYPE eclass variable
	# No -DCMAKE_BUILD_TYPE=xxx definitions will be in effect.
	mycmakeargs=(
		${warn_unused_cli}
		-C "${common_config}"
		-G "$(_generator_to_use)"
		-DCMAKE_INSTALL_PREFIX="${EPREFIX}${PREFIX}"
		-DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}"
		-DCMAKE_INSTALL_DO_STRIP=OFF
		-DCMAKE_USER_MAKE_RULES_OVERRIDE="${build_rules}"
		"$@"
		${MYCMAKEARGS}
		"${mycmakeargs[@]}"
	)

	pushd "${BUILD_DIR}" > /dev/null
	# ehook allowing consumers to modify the cmakeargs, or supress cmake invocation
	if ehook_fire cmake-utils-pre_src_configure ; then
		# do any libdir substitution here at the last possible moment
		local oldcmakearg newcmakearg
		declare -a scratchargs=( )
		for oldcmakearg in "${mycmakeargs[@]}" ; do
			newcmakearg=$(get_libdir_subst "${oldcmakearg}")
			[[ ${oldcmakearg} != ${newcmakearg} ]] && \
				einfo "Substituted cmake argument \"${newcmakearg}\" for \"${oldcmakearg}\"${ABI:+ (ABI=${ABI})}"
			scratchargs+=("${newcmakearg}")
		done
		mycmakeargs=("${scratchargs[@]}")
		unset scratchargs

		einfo "From $(pwd): running ${CMAKE_BINARY} $(
			mg-qm "${mycmakeargs[@]}" "${CMAKE_USE_DIR}"
		)"
		_cmake-utils_do_with_unset_vars "CXX CC CFLAGS CXXFLAGS LD LDFLAGS" \
			"${CMAKE_BINARY}" "${mycmakeargs[@]}" "${CMAKE_USE_DIR}" || die "cmake failed"
	fi
	# ehook allowing consumers to take action just after cmake has run
	ehook_fire cmake-utils-post_src_configure -u
	popd > /dev/null
}

enable_cmake-utils_src_compile() {
	debug-print-function ${FUNCNAME} "$@"

	has src_configure ${CMAKE_EXPF} || cmake-utils_src_configure
	cmake-utils_src_make "$@"
}

_ninjaopts_from_makeopts() {
	if [[ ${NINJAOPTS+set} == set ]]; then
		return 0
	fi
	local ninjaopts=()
	set -- ${MAKEOPTS}
	while (( $# )); do
		case $1 in
			-j|-l|-k)
				ninjaopts+=( $1 $2 )
				shift 2
				;;
			-j*|-l*|-k*)
				ninjaopts+=( $1 )
				shift 1
				;;
			*) shift ;;
		esac
	done
	export NINJAOPTS="${ninjaopts[*]}"
}

# @FUNCTION: ninja_src_make
# @INTERNAL
# @DESCRIPTION:
# Build the package using ninja generator
ninja_src_make() {
	debug-print-function ${FUNCNAME} "$@"

	[[ -e build.ninja ]] || die "build.ninja not found. Error during configure stage."

	_ninjaopts_from_makeopts

	declare -a myninjamakeargs=("${myninjamakeargs[@]}")

	if [[ "${CMAKE_VERBOSE}" != "OFF" ]]; then
		myninjamakeargs+=( ${MAKEOPTS} -v )
	fi
	myninjamakeargs+=("$@")
	if ehook_fire cmake-utils-ninja-pre_src_compile ; then
		# do any libdir substitution here at the last possible moment
		local oldninjamakearg newninjamakearg
		declare -a scratchargs=( )
		for oldninjamakearg in "${myninjamakeargs[@]}" ; do
			newninjamakearg=$(get_libdir_subst "${oldninjamakearg}")
			[[ ${oldninjamakearg} != ${newninjamakearg} ]] && \
				einfo "Substituted ninja argument \"${newninjamakearg}\" for \"${oldninjamakearg}\"${ABI:+ (ABI=${ABI})}"
			scratchargs+=("${newninjamakearg}")
		done
		myninjamakeargs=("${scratchargs[@]}")
		unset scratchargs

		echo ninja "$(mg-qm "${myninjamakeargs[@]}")"
		ninja "${myninjamakeargs[@]}" || die
	fi
	ehook_fire cmake-utils-ninja-post_src_compile -u
}

# @FUNCTION: emake_src_make
# @INTERNAL
# @DESCRIPTION:
# Build the package using make generator
emake_src_make() {
	debug-print-function ${FUNCNAME} "$@"

	declare -a mycmakeemakeargs=("${mycmakemakeargs[@]}" "$@")
	[[ "${CMAKE_VERBOSE}" != "OFF" ]] && mycmakeemakeargs+=(VERBOSE=1)
	if ehook_fire cmake-utils-emake-pre_src_compile ; then
		# do any libdir substitution here at the last possible moment
		local oldcmakeemakearg newcmakeemakearg
		declare -a scratchargs=( )
		for oldcmakeemakearg in "${mycmakeemakeargs[@]}" ; do
			newcmakeemakearg=$(get_libdir_subst "${oldcmakeemakearg}")
			[[ ${oldcmakeemakearg} != ${newcmakeemakearg} ]] && \
				einfo "Substituted emake argument \"${newcmakeemakearg}\" for \"${oldcmakeemakearg}\"${ABI:+ (ABI=${ABI})}"
			scratchargs+=("${newcmakeemakearg}")
		done
		mycmakeemakeargs=("${scratchargs[@]}")
		unset scratchargs

		[[ -e Makefile ]] || die "Makefile not found. Error during configure stage."
		emake "${mycmakeemakeargs[@]}" || die
	fi
	ehook_fire cmake-utils-emake-post_src_compile -u
}

# wrap cmake-utils-{ninja,emake}-{post,pre}_src_compile hooks as a convenience
# to consumers expecting uniform phase-name -> hook name mappings
_cmake-utils-pre_src_compile_hookwrap() {
	local rslt
	case ${CMAKE_MAKEFILE_GENERATOR} in
		ninja)
			declare -a mycompileargs=("${myninjamakeargs[@]}")
			ehook_fire cmake-utils-pre_src_compile
			rslt=$?
			myninjamakeargs=("${mycompileeargs[@]}")
			;;
		emake)
			declare -a mycompileargs=("${mycmakemakeargs[@]}")
			ehook_fire cmake-utils-pre_src_compile
			rslt=$?
			mycmakemakeargs=("${mycompileargs[@]}")
			;;
		*)
			die "unknown CMAKE_MAKEFILE_GENERATOR"
			;;
	esac
	return $rslt
}
ehook cmake-utils-ninja-pre_src_compile _cmake-utils-pre_src_compile_hookwrap
ehook cmake-utils-emake-pre_src_compile _cmake-utils-pre_src_compile_hookwrap
_cmake-utils-post_src_compile_hookwrap() {
	ehook_fire cmake-utils-post_src_compile -u
}
ehook cmake-utils-ninja-post_src_compile _cmake-utils-post_src_compile_hookwrap
ehook cmake-utils-emake-post_src_compile _cmake-utils-post_src_compile_hookwrap

# @FUNCTION: cmake-utils_src_make
# @DESCRIPTION:
# Function for building the package. Automatically detects the build type.
# All arguments are passed to emake.
cmake-utils_src_make() {
	debug-print-function ${FUNCNAME} "$@"

	_check_build_dir
	pushd "${BUILD_DIR}" >/dev/null

	${CMAKE_MAKEFILE_GENERATOR}_src_make "$@"

	popd >/dev/null
}

enable_cmake-utils_src_install() {
	debug-print-function ${FUNCNAME} "$@"

	_check_build_dir
	pushd "${BUILD_DIR}" >/dev/null
	declare -a mycmakeinstallargs=(install "${mycmakeinstallargs[@]}" "$@")
	if [[ "${CMAKE_VERBOSE}" != "OFF" ]] ; then
		case ${CMAKE_MAKEFILE_GENERATOR} in
			ninja) mycmakeinstallargs+=(-v) ;;
			emake) mycmakeinstallargs+=(VERBOSE=1) ;;
		esac
	fi
	if ehook_fire cmake-utils-pre_install ; then
		# do any libdir substitution here at the last possible moment
		local oldcmakeinstallarg newcmakeinstallarg
		declare -a scratchargs=( )
		for oldcmakeinstallarg in "${mycmakeinstallargs[@]}" ; do
			newcmakeinstallarg=$(get_libdir_subst "${oldcmakeinstallarg}")
			[[ ${oldcmakeinstallarg} != ${newcmakeinstallarg} ]] && \
				einfo "Substituted cmake argument \"${newcmakeinstallarg}\" for \"${oldcmakeinstallarg}\"${ABI:+ (ABI=${ABI})}"
			scratchargs+=("${newcmakeinstallarg}")
		done
		mycmakeinstallargs=("${scratchargs[@]}")
		unset scratchargs

		DESTDIR="${D}" ${CMAKE_MAKEFILE_GENERATOR} "${mycmakeinstallargs[@]}" || \
			die "died running ${CMAKE_MAKEFILE_GENERATOR} install"

		# hook allowing consumers to suppress docs installation
		if ehook_fire cmake-utils-pre_install_docs ; then
			pushd "${S}" > /dev/null

		    #Install docs, copied from base_src_install_docs
			local x

		    if [[ "$(declare -p DOCS 2>/dev/null 2>&1)" == "declare -a"* ]]; then
		        for x in "${DOCS[@]}"; do
		            debug-print "$FUNCNAME: docs: creating document from ${x}"
		            dodoc "${x}" || die "dodoc failed"
		        done
		    fi
		    if [[ "$(declare -p HTML_DOCS 2>/dev/null 2>&1)" == "declare -a"* ]]; then
		        for x in "${HTML_DOCS[@]}"; do
		            debug-print "$FUNCNAME: docs: creating html document from ${x}"
		            dohtml -r "${x}" || die "dohtml failed"
		        done
		    fi

			# Backward compatibility, for non-array variables
			if [[ -n "${DOCS}" ]] && [[ "$(declare -p DOCS 2>/dev/null 2>&1)" != "declare -a"* ]]; then
				dodoc ${DOCS} || die "dodoc failed"
			fi
			if [[ -n "${HTML_DOCS}" ]] && [[ "$(declare -p HTML_DOCS 2>/dev/null 2>&1)" != "declare -a"* ]]; then
				dohtml -r ${HTML_DOCS} || die "dohtml failed"
			fi
			popd > /dev/null
		fi
	fi
	ehook_fire cmake-utils-post_install -u
	popd >/dev/null
}

enable_cmake-utils_src_test() {
	debug-print-function ${FUNCNAME} "$@"

	_check_build_dir
	pushd "${BUILD_DIR}" > /dev/null

	declare -a myctestargs=("${myctestargs[@]}" "$@")

	[[ -n ${TEST_VERBOSE} ]] && myctestargs+=( --extra-verbose --output-on-failure )
	if ehook_fire cmake-utils-pre_src_test ; then
		# do any libdir substitution here at the last possible moment
		local oldctestarg newctestarg
		declare -a scratchargs=( )
		for oldctestarg in "${myctestargs[@]}" ; do
			newctestarg=$(get_libdir_subst "${oldctestarg}")
			[[ ${oldctestarg} != ${newctestarg} ]] && \
				einfo "Substituted cmake argument \"${newctestarg}\" for \"${oldctestarg}\"${ABI:+ (ABI=${ABI})}"
			scratchargs+=("${newctestarg}")
		done
		myctestargs=("${scratchargs[@]}")
		unset scratchargs

		[[ -e CTestTestfile.cmake ]] || { echo "No tests found. Skipping."; return 0 ; }

		if ctest "${myctestargs[@]}" ; then
			einfo "Tests succeeded."
		else
			if [[ -n "${CMAKE_YES_I_WANT_TO_SEE_THE_TEST_LOG}" ]] ; then
				# on request from Diego
				eerror "Tests failed. Test log ${BUILD_DIR}/Testing/Temporary/LastTest.log follows:"
				eerror "--START TEST LOG--------------------------------------------------------------"
				cat "${BUILD_DIR}/Testing/Temporary/LastTest.log"
				eerror "--END TEST LOG----------------------------------------------------------------"
				die "Tests failed."
			else
				die "Tests failed. When you file a bug, please attach the following file: \n\t${BUILD_DIR}/Testing/Temporary/LastTest.log"
			fi

			# die might not die due to nonfatal
			ehook_fire cmake-utils-post_src_test -u
			popd > /dev/null
			return 1
		fi
	fi
	ehook_fire cmake-utils-post_src_test -u
	popd > /dev/null
	return 0
}

# @FUNCTION: cmake-utils_src_prepare
# @DESCRIPTION:
# Apply ebuild and user patches.
cmake-utils_src_prepare() {
	debug-print-function "${FUNCNAME}" "$@"
	_execute_optionally "src_prepare" "$@"
}

# @FUNCTION: cmake-utils_src_configure
# @DESCRIPTION:
# General function for configuring with cmake. Default behaviour is to start an
# out-of-source build.
cmake-utils_src_configure() {
	debug-print-function "${FUNCNAME}" "$@"
	_execute_optionally "src_configure" "$@"
}

# @FUNCTION: cmake-utils_src_compile
# @DESCRIPTION:
# General function for compiling with cmake. Default behaviour is to check for
# EAPI and respectively to configure as well or just compile.
# Automatically detects the build type. All arguments are passed to emake.
cmake-utils_src_compile() {
	debug-print-function "${FUNCNAME}" "$@"
	_execute_optionally "src_compile" "$@"
}

# @FUNCTION: cmake-utils_src_install
# @DESCRIPTION:
# Function for installing the package. Automatically detects the build type.
cmake-utils_src_install() {
	debug-print-function "${FUNCNAME}" "$@"
	_execute_optionally "src_install" "$@"
}

# @FUNCTION: cmake-utils_src_test
# @DESCRIPTION:
# Function for testing the package. Automatically detects the build type.
cmake-utils_src_test() {
	debug-print-function "${FUNCNAME}" "$@"
	_execute_optionally "src_test" "$@"
}

# Optionally executes phases based on WANT_CMAKE variable/USE flag.
_execute_optionally() {
	debug-print-function "${FUNCNAME}" "$@"
	local phase="$1" ; shift
	if [[ ${WANT_CMAKE} = always ]]; then
		enable_cmake-utils_${phase} "$@"
	else
		use ${WANT_CMAKE} && enable_cmake-utils_${phase} "$@"
	fi
}

fi