# vim:ts=4 sw=4 noet ft=spec
#
# PLD Linux rpm macros.
# <http://www.pld-linux.org/>

%distribution	PLD Linux
%vendor		pld
%bugurl		http://bugs.pld-linux.org/
%disturl	http://www.pld-linux.org/
%pld_release	th
%disttag	%{pld_release}

# can be used by builder script to check for version
%rpm_build_macros	2.009

%epoch		0

#==============================================================================
# ---- configure macros.  note that most of these are inherited
#      from the defaults.
#
%_sharedstatedir	/var/lib
%_localstatedir		/var
%_localedir			%{_datadir}/locale
%_lispdir			%{_datadir}/emacs/site-lisp
%_initddir			%{_sysconfdir}/rc.d/init.d

%_defaultdocdir		%{_usr}/share/doc

%_fmoddir		%{_libdir}/gfortran/modules

# Location of autoconf macros
%_aclocaldir	%{expand:%%global _aclocaldir %(aclocal --print-ac-dir 2>/dev/null || echo ERROR)}%_aclocaldir

# Location of omf files
%_omf_dest_dir	%{expand:%%global _omf_dest_dir %(scrollkeeper-config --omfdir || echo ERROR)}%_omf_dest_dir

# Location of pkgconfig files
%_pkgconfigdir	/usr/%{_lib}/pkgconfig
# noarch pkgconfig files
%_npkgconfigdir	/usr/share/pkgconfig

# Location of desktop files
%_desktopdir	/usr/share/applications
%_applnkdir	ERROR:_applnkdir_is_obsolete_use_desktopdir_instead

# Location of pixmaps for applnk/desktop files
%_pixmapsdir	/usr/share/pixmaps

# Location of themable icons for applnk/desktop files
%_iconsdir	/usr/share/icons

# Location of fonts directories
%_fontsdir	/usr/share/fonts

# Location of Gtk and associated libraries documentation
%_gtkdocdir	%{_defaultdocdir}/gtk-doc/html

# Location of KDE documentation
%_kdedocdir	%{_defaultdocdir}/kde/HTML

# unsermake script
%__unsermake /usr/share/unsermake/unsermake

# Current date
%date		%(LC_ALL=C date +"%a %b %d %Y")

# Example files, programs, scripts...
%_examplesdir	/usr/src/examples

# SysV-style initscripts dir
%_initddir		/etc/rc.d/init.d

# Executed at after copying %doc to DOCDIR, with $DOCDIR set
# TODO: teach rpm.org that compressed %doc is the same thing as uncompressed
#__compress_doc		%{_rpmconfigdir}/compress-doc%{?_noautocompressdoc: --noautocompressdoc='%{_noautocompressdoc}'}

%__os_install_post \
%{__spec_install_post_strip}\
%{__spec_install_post_chrpath}\
%{__spec_install_post_compress_modules}\
%{__spec_install_post_check_so}\
%{__spec_install_post_check_tmpfiles}\
%{__spec_install_post_check_shebangs}\
%{__spec_install_post_compress_docs}\
%{__spec_install_post_py_hardlink}\
%{__spec_install_post_perl_clean}\
%{__arch_install_post}\
%{nil}

%__spec_install_post\
%{expand:%%define __sip_%{?_enable_debug_packages} 1}%{?__sip_1:%{?__debug_package:%{__debug_install_post}}}%{expand:%%undefine __sip_%{?_enable_debug_packages}}\
%{__arch_install_post}\
%{__os_install_post}\
%{nil}

#---------------------------------------------------------------------
#	Template for debug information sub-package.
%_enable_debug_packages		1

%_debuginfo_template \
%package debuginfo\
Summary: Debug information for package %{name}\
Summary(pl.UTF-8): Informacje dla debuggera dla pakietu %{name}\
Group: Development/Debug\
Requires: filesystem-debuginfo >= 3.0-16\
AutoReqProv: 0\
%description debuginfo\
This package provides debug information for package %{name}.\
Debug information is useful when developing applications that use this\
package or when debugging this package.\
%description debuginfo -l pl.UTF-8\
Ten pakiet dostarcza informacje dla debuggera dla pakietu %{name}.\
Informacje te są przydatne przy rozwijaniu aplikacji używających tego\
pakietu oraz przy odpluskwianiu samego pakietu.\
%files debuginfo -f debugfiles.list\
%defattr(-,root,root)\
%{nil}

%_debugsource_template \
%package debugsource\
Summary: Debug sources for package %{name}\
Summary(pl.UTF-8): Źródła dla debuggera dla pakietu %{name}\
Group: Development/Debug\
AutoReqProv: 0\
%description debugsource\
This package provides debug sources for package %{name}.\
Debug sources are useful when developing applications that use this\
package or when debugging this package.\
%description debugsource -l pl.UTF-8\
Ten pakiet dostarcza źródła dla debuggera dla pakietu %{name}.\
Źródła te są przydatne przy rozwijaniu aplikacji używających tego\
pakietu oraz przy odpluskwianiu samego pakietu.\
%files debugsource -f debugsourcefiles.list\
%{nil}

%debug_package \
%ifnarch noarch\
%global __debug_package 1\
%_debuginfo_template\
%if 0%{?_debugsource_packages}\
%_debugsource_template\
%endif\
%endif\
%{nil}

#---------------------------------------------------------------------
# Overwrite RPM macros with PLD specific one here.

%__find			/usr/bin/find
%__lua			%{_bindir}/lua
%__rc			%{_bindir}/rc
%__xar			%{_bindir}/xar

%_source_payload	w9.gzdio
%_binary_payload	w6.xzdio

%_rpmfc_magic_path	/usr/share/file/magic

# provides don't obsolete
%_upgrade_tag		name

# Disable automatic dependencies on symlinks for now (debuginfo packages pull too many deps)
%_check_symlink_deps    0 
 
# Do not generate executable() dependencies for scriptlets,
# as it may give false positives, for example:
# [ ! -x /bin/prog ] || /bin/prog
# will generate R:/bin/prog and we don't want that as /bin/prog is optional in this case
# 0 - Use external generator
# 1 - Use internal generator if available
# 2 - Use __scriptlet_requires to process scriptlet dependencies
%_use_internal_dependency_generator	1

%_duplicate_files_terminate_build	1
%_files_listed_twice_terminate_build	1
%_unpackaged_files_terminate_build	0
%_unpackaged_subdirs_terminate_build	0

#
# Export package NEVRA (stamped with install tid) info for HRMIB on this path.
#
# XXX	Note: escaped %% for use in headerSprintf()
%_hrmib_path	/var/cache/hrmib/%{___NVRA}

#-----------------------------------------------------------------
# CFLAGS and LDFLAGS used to build

%debuginfocflags	%{expand:%%define __dic_%{?_enable_debug_packages} 1}%{?__dic_1: -gdwarf-4 -fno-debug-types-section -fvar-tracking-assignments -g2}%{expand:%%undefine __dic_%{?_enable_debug_packages}}
# -feliminate-dwarf2-dups disabled until PR ld/3290 is fixed.

%debugcflags	-O0 -g -Wall
%debugcppflags	%{nil}
%debugldflags	%{nil}

%optldflags	-Wl,--as-needed -Wl,--no-copy-dt-needed-entries -Wl,-z,relro -Wl,-z,combreloc
%optcppflags	%{nil}

# common compilation flags
%_fortify_cflags	-Wp,-D_FORTIFY_SOURCE=2

# cf http://wiki.mandriva.com/en/Development/Packaging/Problems#format_not_a_string_literal_and_no_format_arguments
%Werror_cflags		-Wformat -Werror=format-security

# Use -Werror=trampolines to prevent GCC from generating code that require executable stack
%_ssp_cflags		-fstack-protector-strong --param=ssp-buffer-size=4 -Werror=trampolines
%__common_cflags	-O2 -fwrapv -pipe %{Werror_cflags} %{debuginfocflags} %{?_fortify_cflags} %{!?nospecflags:%{?specflags}}
%__common_cflags_with_ssp	%{__common_cflags} %{?_ssp_cflags}

# arch macros
%ix86  i386 i486 i586 i686 pentium3 pentium4 athlon geode
%x8664 x86_64 amd64 ia32e
%ppc   ppc ppc7400 ppc7450

# avoid fdatasync syscall flood during database operations.
%__nofsync	nofsync

#---------------------------------------------------------------------
#	Expanded at end of %prep
#
%__chown_Rhf	%{__chown} -Rhf
%__chgrp_Rhf	%{__chgrp} -Rhf
%_fixowner	[ `%{__id_u}` = '0' ] && %{__chown_Rhf} root
%_fixgroup	[ `%{__id_u}` = '0' ] && %{__chgrp_Rhf} root

# compiler version
%cc_version	%{expand:%%global cc_version %(%{__cc} -dumpversion 2>/dev/null || echo 0.0)}%cc_version
%cxx_version	%{expand:%%global cxx_version %(%{__cxx} -dumpversion 2>/dev/null || echo 0.0)}%cxx_version

%__rm		/bin/rm --interactive=never

# Build system path macros.
%__autoconf		autoconf %{?debug:-Wall}
%__automake		automake -a -c -f --foreign
%__autopoint	autopoint --force
%__aclocal		aclocal
%__autoheader	autoheader

# add parallel build flags: -jN
# jobs macro is available since 1.657
#
# if you want to disable parallel build do:
# echo '%__jobs %{nil}' >> ~/.rpmmacros
%__jobs		%{expand:%%global __jobs %(_NCPUS=$(/usr/bin/getconf _NPROCESSORS_ONLN); [ "$_NCPUS" -gt 3 ] && echo $(($_NCPUS / 2)))%%{nil}}%__jobs

# expands to -jN if %__jobs has a value
%_smp_mflags	%{expand:%%global _smp_mflags %(jobs=%{__jobs}; echo ${jobs:+-j$jobs}%%{nil})}%_smp_mflags

%__make		/usr/bin/make %{?_make_opts} %{?_smp_mflags}
%__scons	/usr/bin/scons %{?_smp_mflags}
%__waf		/usr/bin/waf %{?_smp_mflags}
%__cmake	/usr/bin/cmake
%__meson	/usr/bin/meson
%__meson_wrap_mode	nodownload
%__ninja	/usr/bin/ninja
%__ninja_common_opts	-v %{?_smp_mflags}

%__gettextize { \
	gettextize --copy --force --no-changelog; \
	if [ ! -f po/Makevars ]; then \
		cp -f po/Makevars{.template,}; \
	fi; \
}

%__glib_gettextize	glib-gettextize --copy --force
%__gnome_doc_common	gnome-doc-common --copy
%__gnome_doc_prepare	gnome-doc-prepare --copy --force
%__gtkdocize		gtkdocize --copy
%__intltoolize		intltoolize --copy --force
%__libtoolize		libtoolize --copy --force --install

# topdir is where builder script lives,
# fallback to old style if SPECS/SOURCES dirs were found.
%_topdir    %{expand:%%global _topdir %(
	if [ -d SPECS -a -d SOURCES ]; then
		# old style rpmdir: in topdir
		pwd
	elif [ -d ../SPECS -a -d ../SOURCES ]; then
		# old style rpmdir: in subdir
		cd ..; pwd
	elif [ -d $HOME/rpm/SPECS -a -d $HOME/rpm/SOURCES ]; then \
		# if old style rpm dir exist, go with it
		echo $HOME/rpm; \
	elif [ -x ../builder -a ! -d ../builder ]; then
		# relative new style rpmdir: in package dir
		cd ..; pwd
	elif [ -x builder -a ! -d builder ]; then
		# relative new style rpmdir: in packages
		pwd
	elif [ -x packages/builder -a ! -d packages/builder ]; then
		# relative new style rpmdir: packages dir in current dir
		cd packages; pwd
	else
		# fallback to new style rpmdir
		echo $HOME/rpm/packages
	fi; \
)}%_topdir

%_tmppath		%(echo "${TMPDIR:-/var/tmp}")
%tmpdir			%{_tmppath}

%_buildrootdir	%{_tmppath}
%buildroot		%{_buildrootdir}/%{name}-%{version}-%{_arch}-root-%(id -u -n)

# if %{_topdir}/SPECS exists, it's old style structure
%_specdir		%{expand:%%global _specdir %([ ! -d %{_topdir}/SPECS ] && echo %{_topdir}/%{name} || echo %{_topdir}/SPECS)}%_specdir
%_sourcedir		%{expand:%%global _sourcedir %([ ! -d %{_topdir}/SOURCES ] && echo %{_specdir} || echo %{_topdir}/SOURCES)}%_sourcedir

# BUILD/RPMS/SRPMS are on same level by default as packages dir, if these exist
# if they don't exist assume we are having custom topdir (which is not named as
# "packages", i.e ~/rpm/kde/{kdelibs,BUILD/RPMS/SRPMS})
# NOTE: readlink fails if some parent dir is not readable (/home/services/builder for example can't read /home/services), therefore the extra echo
%_builddir		%{expand:%%global _builddir %(if [ -d %{_topdir}/BUILD ]; then echo %{_topdir}/BUILD; else readlink -m %{_topdir}/../BUILD || echo %{_topdir}/../BUILD; fi)}%_builddir
%_rpmdir		%{expand:%%global _rpmdir %(if [ -d %{_topdir}/RPMS ]; then echo %{_topdir}/RPMS; else readlink -m %{_topdir}/../RPMS || echo readlink -m %{_topdir}/../RPMS; fi)}%_rpmdir
%_srcrpmdir		%{expand:%%global _srcrpmdir %(if [ -d %{_topdir}/SRPMS ]; then echo %{_topdir}/SRPMS; else readlink -m %{_topdir}/../SRPMS || echo readlink -m %{_topdir}/../SRPMS; fi)}%_srcrpmdir

#	The number of cvs changelog entries kept when building package.
%_buildchangelogtruncate 20

%dependencytracking	%{nil}

#	Relations between package names that cause dependency loops
#	with legacy packages that cannot be fixed. Relations are
#	specified as
#		p>q
#	where package p has a Requires: on something that package q Provides:
#
# XXX	Note: that there cannot be any whitespace within the string "p>q",
#	and that both p and q are package names (i.e. no version/release).
%_dependency_whiteout	%{nil}

#-----------------------------------------------------------------
#
# (re)definition of %{rpm*flags} with %filterout_* support
# BuildRequires:	awk
# BuildRequires:	rpmbuild(macros) >= 1.315
#
# Flags specified in %filterout_* are removed from %rpm*flags, exactly:
# %rpmcflags    = %optflags - %filterout - %filterout_c   - %filterout_ld
# %rpmcxxflags  = %optflags - %filterout - %filterout_cxx - %filterout_ld
# %rpmcppflags  = %optcppflags - %filterout - %filterout_cpp - %filterout_ld
# %rpmldflags   = %optldflags - %filterout_ld
#
# Regular expressions are supported, but to avoid some character be treated
# as regular expression it must be escaped twice.

%filter_out							\
	for (i = 1; i in I; i++) { A=0;	\
		for (f in F) {				\
			if (I[i] ~ "^" F[f] "$") A=1;	\
		};							\
		if (!A) printf(I[i] FS);	\
	}

%rpmcflags %(awk 'BEGIN {
	split("%{?debug:%debugcflags}%{!?debug:%optflags}%{?debuginfocflags}",I);
	split("%{?filterout} %{?filterout_c} %{?filterout_ld}",F);
	%{filter_out}
}')

%rpmcxxflags %(awk 'BEGIN {
	split("%{?debug:%debugcflags}%{!?debug:%optflags}%{?debuginfocflags}",I);
	split("%{?filterout} %{?filterout_cxx} %{?filterout_ld}",F);
	%{filter_out}
}')

%rpmcppflags %(awk 'BEGIN {
	split("%{?debug:%debugcppflags}%{!?debug:%optcppflags}%{?debuginfocppflags}",I);
	split("%{?filterout} %{?filterout_cpp} %{?filterout_cpp}",F);
	%{filter_out}
}')

%rpmldflags %(awk 'BEGIN {
	split("%{?optldflags}",I);
	split("%{?filterout_ld}",F)
	%{filter_out}
}')

# rpmldflags with stripped -Wl, -- in the form flags have to be passed to 'ld'
# but, don't use it, better use gcc as linker
%ld_rpmldflags %(awk 'BEGIN {
        split("%{rpmldflags}",F);
        for (f in F) {
                s = F[f];
                if (s ~ /^-Wl,/) {
                        s = substr(s,5);
                        gsub(/,/," ",s);
                };
                printf(s FS);
        };
}')

#-----------------------------------------------------------------
#
#  Generate a command which cleans environment, leaving only the
# most important variables.
#  If any spec requires any additional environment it should
# redefine %_preserve_env in following manner:
#
#	# ADDITIONAL_VAR is required because [a good reason here]
#	%define _preserve_env ADDITIONAL_VAR

%_preserve_env_base	PATH HOME TMP TMPDIR SSH_AUTH_SOCK

# "env -i" must end in first line of expaned macros because it's used as first line of shell script (#! env...)
%_clean_env env -i %(awk -vq="'" -vqq="\\"'\\"" -vq2q="'\\"'" 'BEGIN {
	split("%{?_preserve_env:%_preserve_env %_preserve_env_base}%{!?_preserve_env:%_preserve_env_base}", P);
	for (i in P) {
		p = P[i];
		if (!ENVIRON[p] || d[p]) {
			continue;
		}
		d[p] = 1;
		split(ENVIRON[p], V, "");
		val = p "=";
		for (j = 1; j in V; j++) {
			v = V[j];
			if (v == q)
				v = qq;
			else if (v == "\\"")
				v = q2q;
			else if (v == "\\\\")
				v = "\\\\\\\\";
			else
				gsub("[^a-zA-Z0-9/:._-]", "\\"&\\"", v);
			val = val "" v;
		}
		printf(val " ");
	}
}')

# override %__spec_build_pre and %__spec_install_pre from macros.rpmbuild
# adding %{_clean_env}
%__spec_build_pre	%{_clean_env}\
%{___build_pre}\
%{nil}
%__spec_install_pre	%{_clean_env}\
%{___build_pre}\
%{?buildroot:%{__rm} -rf '%{buildroot}'; %{__mkdir_p} '%{buildroot}'}\
%{nil}

#-----------------------------------------------------------------
%configure2_13 { \
 if [ -n "$LINGUAS" ]; then unset LINGUAS; fi; \
 LDFLAGS="${LDFLAGS:-%rpmldflags}" ; export LDFLAGS ; \
 CFLAGS="${CFLAGS:-%rpmcflags}" ; export CFLAGS ; \
 CXXFLAGS="${CXXFLAGS:-%rpmcxxflags}" ; export CXXFLAGS ; \
 FFLAGS="${FFLAGS:-%rpmcflags}" ; export FFLAGS ; \
 FCFLAGS="${FCFLAGS:-%rpmcflags}" ; export FCFLAGS ; \
 CPPFLAGS="${CPPFLAGS:-%rpmcppflags}" ; export CPPFLAGS ; \
 %{?__cc:CC="%{__cc}" ; export CC ; } \
 %{?__cxx:CXX="%{__cxx}" ; export CXX ; } \
 %{?configuredir:%{configuredir}}%{!?configuredir:.}/configure \
	--host=%{_target_platform} \
	--prefix=%{_prefix} \
	--exec-prefix=%{_exec_prefix} \
	--bindir=%{_bindir} \
	--sbindir=%{_sbindir} \
	--sysconfdir=%{_sysconfdir} \
	--datadir=%{_datadir} \
	--includedir=%{_includedir} \
	--libdir=%{_libdir} \
	--libexecdir=%{_libexecdir} \
	--localstatedir=%{_localstatedir} \
	--sharedstatedir=%{_sharedstatedir} \
	--mandir=%{_mandir} \
	--infodir=%{_infodir} \
	--x-libraries=%{?_x_libraries}%{!?_x_libraries:%{_libdir}} \
	%{dependencytracking} \
}

# Note: pass only standard cmake macros here.
# The only exception is SYSCONF_INSTALL_DIR, used commonly in KDE packages,
# where the default (${CMAKE_INSTALL_PREFIX}/etc) is not FHS-compliant and
# absolute path MUST be used to comply with FHS.
# The other non-standard cmake macros used commonly in KDE
# (INCLUDE_INSTALL_DIR, LIB_INSTALL_DIR, SHARE_INSTALL_PREFIX)
# have sane default values in KDE, and some packages use these names
# in different way (e.g. expect them to be always relative or always
# absolute).
%cmake \
%{?__cc:CC="${CC:-%{__cc}}"} \\\
%{?__cxx:CXX="${CXX:-%{__cxx}}"} \\\
CPPFLAGS="${CPPFLAGS:-%{rpmcppflags}}" \\\
%{__cmake} \\\
	-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON \\\
	-DCMAKE_BUILD_TYPE=%{!?debug:PLD}%{?debug:Debug} \\\
	-DCMAKE_INSTALL_BINDIR:PATH=%{_bindir} \\\
	-DCMAKE_INSTALL_SBINDIR:PATH=%{_sbindir} \\\
	-DCMAKE_INSTALL_LIBEXECDIR:PATH=%{_libexecdir} \\\
	-DCMAKE_INSTALL_SYSCONFDIR:PATH=%{_sysconfdir} \\\
	-DCMAKE_INSTALL_SHAREDSTATEDIRPATH:PATH=%{_sharedstatedir} \\\
	-DCMAKE_INSTALL_LOCALSTATEDIRPATH:PATH=%{_localstatedir} \\\
	-DCMAKE_INSTALL_LIBDIR:PATH=%{_libdir} \\\
	-DCMAKE_INSTALL_INCLUDEDIR:PATH=%{_includedir} \\\
	-DCMAKE_INSTALL_OLDINCLUDEDIR:PATH=%{_includedir} \\\
	-DCMAKE_INSTALL_DATAROOTDIR:PATH=%{_datadir} \\\
	-DCMAKE_INSTALL_DATADIR:PATH=%{_datadir} \\\
	-DCMAKE_INSTALL_INFODIR:PATH=%{_infodir} \\\
	-DCMAKE_INSTALL_LOCALEDIR:PATH=%{_localedir} \\\
	-DCMAKE_INSTALL_MANDIR:PATH=%{_mandir} \\\
	-DCMAKE_INSTALL_DOCDIR:PATH=%{_docdir} \\\
	-DCMAKE_INSTALL_PREFIX:PATH=%{_prefix} \\\
	-DSYSCONF_INSTALL_DIR:PATH=%{_sysconfdir} \\\
	-DCMAKE_CXX_FLAGS_PLD="${CXXFLAGS:-%{rpmcxxflags} -DNDEBUG -DQT_NO_DEBUG}" \\\
	-DCMAKE_C_FLAGS_PLD="${CFLAGS:-%{rpmcflags} -DNDEBUG -DQT_NO_DEBUG}" \\\
	-DCMAKE_Fortran_FLAGS_PLD="${CFLAGS:-%{rpmcflags} -DNDEBUG -DQT_NO_DEBUG}" \\\
	-DCMAKE_EXE_LINKER_FLAGS_PLD="${LDFLAGS:-%{rpmldflags}}" \\\
	-DCMAKE_SHARED_LINKER_FLAGS_PLD="${LDFLAGS:-%{rpmldflags}}" \\\
	-DCMAKE_MODULE_LINKER_FLAGS_PLD="${LDFLAGS:-%{rpmldflags}}" \\\
%if "%{_lib}" == "lib64" \
	-DLIB_SUFFIX=64 \\\
%endif \
%if "%{_lib}" == "libx32" \
	-DLIB_SUFFIX=x32 \\\
%endif \
	-DBUILD_SHARED_LIBS:BOOL=ON \\\
%{nil}

%scons { \
%{__scons} \
	LDFLAGS="${LDFLAGS:-%rpmldflags}" \
	CFLAGS="${CFLAGS:-%rpmcflags}" \
	CXXFLAGS="${CXXFLAGS:-%rpmcxxflags}" \
	FFLAGS="${FFLAGS:-%rpmcflags}" \
	CPPFLAGS="${CPPFLAGS:-%rpmcppflags}" \
	%{?__cc:CC="%{__cc}"} \
	%{?__cxx:CXX="%{__cxx}"} \
	libsuffix=%{_lib} \
	prefix=%{_prefix} \
}

# waf. see waf.spec
%waf { \
CC="%{__cc}" \
CXX="%{__cxx}" \
CPP="%{__cpp}" \
CFLAGS="%{rpmcflags}" \
CXXFLAGS="%{rpmcxxflags}" \
LINKFLAGS="%{rpmldflags}" \
%{__waf} \
}

# meson
%meson { \
%{?__cc:CC="${CC:-%{__cc}}"} \
%{?__cxx:CXX="${CXX:-%{__cxx}}"} \
CFLAGS="${CFLAGS:-%{rpmcflags}}" \
CPPFLAGS="${CPPFLAGS:-%{rpmcppflags}}" \
CXXFLAGS="${CXXFLAGS:-%{rpmcxxflags}}" \
LDFLAGS="${LDFLAGS:-%{rpmldflags}}" \
LC_ALL=C.UTF-8 %{__meson} \
	--buildtype=plain \
	--bindir=%{_bindir} \
	--datadir=%{_datadir} \
	--includedir=%{_includedir} \
	--infodir=%{_infodir} \
	--libdir=%{_libdir} \
	--libexecdir=%{_libexecdir} \
	--localedir=%{_localedir} \
	--localstatedir=%{_localstatedir} \
	--mandir=%{_mandir} \
	--prefix=%{_prefix} \
	--sbindir=%{_sbindir} \
	--sharedstatedir=%{_sharedstatedir} \
	--sysconfdir=%{_sysconfdir} \
	--wrap-mode=%{__meson_wrap_mode} \
	--default-library='both' \
}

%___meson_deprecate() {echo >&2 "DEPRECATED: %%%1 must be replaced with %%%2"; %{expand:%%%2} }
%meson_build %___meson_deprecate meson_build ninja_build
%meson_install %___meson_deprecate meson_install ninja_install
%meson_test %___meson_deprecate meson_test ninja_test

# ninja
%ninja_build LC_ALL=C.UTF-8 %{__ninja} %{__ninja_common_opts}
%ninja_install LC_ALL=C.UTF-8 DESTDIR=%{buildroot} %{__ninja} install %{__ninja_common_opts}
%ninja_test LC_ALL=C.UTF-8 %{__ninja} test %{__ninja_common_opts}

#----------------------------------------------------------------
#%configure_cache 0
%configure_cache_file	%{buildroot}.configure.cache

%configure {./configure \
	LDFLAGS="${LDFLAGS:-%rpmldflags}" \
	CFLAGS="${CFLAGS:-%rpmcflags}" \
	CXXFLAGS="${CXXFLAGS:-%rpmcxxflags}" \
	FFLAGS="${FFLAGS:-%rpmcflags}" \
	FCFLAGS="${FCFLAGS:-%rpmcflags}" \
	CPPFLAGS="${CPPFLAGS:-%rpmcppflags}" \
	%{?__cc:CC="%{__cc}"} \
	%{?__cxx:CXX="%{__cxx}"} \
	--host=%{_target_platform} \
	--build=%{_target_platform} \
	--prefix=%{_prefix} \
	--exec-prefix=%{_exec_prefix} \
	--bindir=%{_bindir} \
	--sbindir=%{_sbindir} \
	--sysconfdir=%{_sysconfdir} \
	--datadir=%{_datadir} \
	--includedir=%{_includedir} \
	--libdir=%{_libdir} \
	--libexecdir=%{_libexecdir} \
	--localstatedir=%{_localstatedir} \
	--sharedstatedir=%{_sharedstatedir} \
	--mandir=%{_mandir} \
	--infodir=%{_infodir} \
	--x-libraries=%{?_x_libraries}%{!?_x_libraries:%{_libdir}} \
	%{dependencytracking} \
	%{?configure_cache:--cache-file=%{configure_cache_file}} \
}

# Simple macros to simplify adding bconded options to configure scripts.
#   Each macro requires bcond name and accepts optional option name, if option
# isn't specified bcond name is used as option name. Options returning
# --with and --enable also allow third argument which will be added as value
# ( --with-option=value or --enable-option=value ) in case or positive
# condition, but won't be added otherwise ( nothing or just --disable-option ).

# Requirements:
# BuildRequires: rpmbuild(macros) >= 1.527

# Usage example:
# %{__enable bcond} - returns --enable-bcond iff build condition is set
# %{__disable bcond option} - returns --enable-option iff bcond is not set
# %{__enable_disable bcond option value} - returns --enable-option=value if
#    bcond is set, returns --disable-option otherwise

# expand bconds to --enable-something and --disable-something
%__enable() %{expand:%%{?with_%{1}:--enable-%{?2}%{!?2:%{1}}%{?3:=%{3}}}}
%__disable() %{expand:%%{!?with_%{1}:--disable-%{?2}%{!?2:%{1}}}}
%__enable_disable() %{expand:%%{?with_%{1}:--enable-%{?2}%{!?2:%{1}}%{?3:=%{3}}}%%{!?with_%{1}:--disable-%{?2}%{!?2:%{1}}}}

# same as above, but condition inverted
%__enable_unless() %{expand:%%{!?with_%{1}:--enable-%{?2}%{!?2:%{1}}%{?3:=%{3}}}}
%__disable_if() %{expand:%%{?with_%{1}:--disable-%{?2}%{!?2:%{1}}}}
%__enable_disable_not() %{expand:%%{!?with_%{1}:--enable-%{?2}%{!?2:%{1}}%{?3:=%{3}}}%%{?with_%{1}:--disable-%{?2}%{!?2:%{1}}}}

# expand bconds to --with-something and --without-something
%__with() %{expand:%%{?with_%{1}:--with-%{?2}%{!?2:%{1}}%{?3:=%{3}}}}
%__without() %{expand:%%{!?with_%{1}:--without-%{?2}%{!?2:%{1}}}}
%__with_without() %{expand:%%{?with_%{1}:--with-%{?2}%{!?2:%{1}}%{?3:=%{3}}}%%{!?with_%{1}:--without-%{?2}%{!?2:%{1}}}}

# same as above, but condition inverted
%__with_unless() %{expand:%%{!?with_%{1}:--with-%{?2}%{!?2:%{1}}%{?3:=%{3}}}}
%__without_if() %{expand:%%{?with_%{1}:--without-%{?2}%{!?2:%{1}}}}
%__with_without_not() %{expand:%%{!?with_%{1}:--with-%{?2}%{!?2:%{1}}%{?3:=%{3}}}%%{?with_%{1}:--without-%{?2}%{!?2:%{1}}}}

# expands to true or false based on bcond; for use with meson or cmake
%__true_false() %{expand:%%{?with_%{1}:true}%%{!?with_%{1}:false}}
%__true_false_not() %{expand:%%{?with_%{1}:false}%%{!?with_%{1}:true}}

# expands to enabled or disabled based on bcond; for use with meson or cmake
%__enabled_disabled() %{expand:%%{?with_%{1}:enabled}%%{!?with_%{1}:disabled}}
%__enabled_disabled_not() %{expand:%%{?with_%{1}:disabled}%%{!?with_%{1}:enabled}}

# for use with cmake:
# Usage: cmake_on_off BCOND_NAME [OPTION_NAME]
# BuildRequires: rpmbuild(macros) >= 1.742
%cmake_on_off() -D%{?2}%{!?2:%{1}}:BOOL=%{expand:%%{?with_%{1}:ON}%%{!?with_%{1}:OFF}}

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

# overload to insert debuginfo package
%prep \
%if 0%{?_enable_debug_packages}\
%{debug_package}\
%endif\
%%prep\
%{nil}

%_build_id_links	%{expand:%%define __dic_%{?_enable_debug_packages} 1}%{?__dic_1:alldebug}%{?__dic_0:none}%{expand:%%undefine __dic_%{?_enable_debug_packages}}

# If non-empty "debug" macro defined, add "dbg" suffix to release number
%_rpmfilename		%%{NAME}-%%{VERSION}-%%{RELEASE}%{?debug:dbg}.%%{ARCH}.rpm

# Bootstrap release macros.
# Usage:
#	%bcond_with	bootstrap
#	Release:	%{bootstrap_release 1}
#
# Package will have release 1 if built normally,
# and release 0.zzz.bootstrap if built with bootstrap
%bootstrap_release() %{!?with_bootstrap:%{1}%{?2:.%{2}}}%{?with_bootstrap:%{!?2:%(expr %{1} - 1)}%{?2:%{1}.%(expr %{2} - 1)}.zzz.bootstrap}

# Requires name = version-release
%requires_releq()	%{!?1:ERROR}%{?2:ERROR}%{?1:%{!?2:%{expand:%%requires_eq_to -r %1 %1}}}
# Requires: name = version
%requires_eq()		%{!?1:ERROR}%{?2:ERROR}%{?1:%{!?2:%{expand:%%requires_eq_to %1 %1}}}
# Requires: name = version (version based on querying package %2)
%requires_eq_to(r)	%{!?2:ERROR}%{?3:ERROR}%{?2:%{!?3:%(if ! LC_ALL=C rpm -q --qf 'Requires: %1 = %|E?{%{E}:}|%{V}%{?-r:-%{R}}\\n' %2 | grep '^Requires:'; then echo "BuildRequires: %2"; fi)}}

# Requires: name >= version
%requires_ge()		%{!?1:ERROR}%{?2:ERROR}%{?1:%{!?2:%{expand:%%requires_ge_to %1 %1}}}
# Requires: name >= version (version based on querying package %2)
%requires_ge_to(r)	%{!?2:ERROR}%{?3:ERROR}%{?2:%{!?3:%(if ! LC_ALL=C rpm -q --qf 'Requires: %1 >= %|E?{%{E}:}|%{V}%{?-r:-%{R}}\\n' %2 | grep '^Requires:'; then echo "BuildRequires: %2"; fi)}}

# helper for renaming packages
# %rename old-package
%rename() \
Obsoletes: %{1} < %{?epoch:%{epoch}:}%{?version:%{version}}%{?release:-%{release}} \
Provides: %{1} = %{?epoch:%{epoch}:}%{?version:%{version}}%{?release:-%{release}}

# for package versions comparison (incl. cc_version or _rpmversion)
# BuildRequires:	rpmbuild(macros) >= 1.749
%_ver_lt()	%(test $(rpmvercmp "%{1}" "%{2}" >/dev/null 2>&1; echo $?) -ne 2; echo $?)
%_ver_ge()	%(test $(rpmvercmp "%{1}" "%{2}" >/dev/null 2>&1; echo $?) -eq 2; echo $?)

# noarch subpackage helper
# BuildRequires:	rpmbuild(macros) >= 1.752
%noarchpackage \
BuildArch:		noarch \
%{nil}

%apache_modules_api %{expand:%%global apache_modules_api %(awk '/#define MODULE_MAGIC_NUMBER_MAJOR/ {print $3}' /usr/include/apache/ap_mmn.h 2>/dev/null || echo ERROR)}%apache_modules_api

# sgml macros
%xmlcat_add()		/usr/bin/xmlcatalog --noout --add nextCatalog \"\" %1 /etc/xml/catalog ;
%xmlcat_del()		/usr/bin/xmlcatalog --noout --del %1 /etc/xml/catalog ;
%xmlcat_add_rewrite	/usr/bin/xmlcatalog --noout --add rewriteSystem
%xmlcat_create()	/usr/bin/xmlcatalog --noout --create %1 ;
%sgmlcat_add()		/usr/bin/install-catalog --add %1 %2 > /dev/null ;
%sgmlcat_del()		/usr/bin/install-catalog --remove %1 %2 > /dev/null ;
%docbook_sgmlcat_fix() { for l in \
'' \
'  -- default decl --' \
'DTDDECL "-//OASIS//DTD DocBook XML V%2//EN" "../../xml.dcl"' \
'  -- hacks for opensp --' \
'SYSTEM "file://%{_datadir}/sgml/docbook/xml-dtd-%2/docbookx.dtd" "%{_datadir}/sgml/docbook/xml-dtd-%2/docbookx.dtd"' \
'SYSTEM   "http://www.oasis-open.org/docbook/xml/%2/docbookx.dtd" "%{_datadir}/sgml/docbook/xml-dtd-%2/docbookx.dtd"' \
'' \
; do echo $l; done >> %1 \
}

# vim - "

# minimum file size needed for compressed documents.
# just smaller files than this get larger when compressed.
# some stats:
# - 0 byte file compressed was 25 bytes .gz
# - 39 byte file was compressed as 57
# - with test/test.spec@man 158 byte file was compressed also 158
%_min_compress_bytes	159

#-----------------------------------------------------------------
# find and gzip all files in %{_mandir} and %{infodir}
#
# Requires: xargs, find
#
#%no_install_post_compress_docs	1
%__spec_install_post_compress_docs { \
%{!?no_install_post_compress_docs:__spec_install_post_compress_docs() { \
	%{!?debug:set +x;} \
	for i in /usr/share/man /usr/X11R6/man; do \
		if [ -d "$RPM_BUILD_ROOT$i" ]; then \
			echo "Compress man pages: $i"; \
			find "$RPM_BUILD_ROOT$i" -name '*.bz2' -print0 | xargs -0 -r %{__bzip2} -df; \
			find "$RPM_BUILD_ROOT$i" -name '*.gz' -print0 | xargs -0 -r %{__gzip} -dnf; \
			find $RPM_BUILD_ROOT$i -type l | while read a; do \
				m=$(readlink "$a"); \
				if [[ "$m" = */* ]]; then \
					# handle links to different man section \
					l=$(readlink -f "$a"); \
					# full/relative paths that resolve symlink \
					l=${l#$RPM_BUILD_ROOT/usr/share/man/}; \
					l=${l#$RPM_BUILD_ROOT/usr/X11R6/man/}; \
					# full paths that do not resolve symlink \
					l=${l#/usr/share/man/}; \
					l=${l#/usr/X11R6/man/}; \
				else \
					l=${a#$RPM_BUILD_ROOT$i/}; \
					l=${l%/*}; \
					l="$l/$m"; \
				fi; \
				rm -f $a; \
				echo ".so $l" > $a; \
				echo >&2 "Converted ${a#$RPM_BUILD_ROOT} from symlink to man link: $l"; \
			done; \
			# verify that .so links point to existing files (not allowed to point to "other package") \
			# TODO: iterate over all man dirs, but in Th there is only one true man dir \
			err=$(grep -rl '^\.so ' "$RPM_BUILD_ROOT$i" | while read doc; do \
				l=$(grep -r '^\.so ' "$doc"); \
				l=${l#.so }; \
				d=$(dirname $doc); \
				test -e $RPM_BUILD_ROOT$i/$l || test -e $d/$(basename $l) || echo "  ${doc#$RPM_BUILD_ROOT} points to inexistent manpage: $l"; \
			done); \
			test "$err" != "" && { echo >&2 "Man page link errors:"; echo >&2 "$err"; exit 1; }; \
			find "$RPM_BUILD_ROOT$i" -type f -size +%{_min_compress_bytes}c -print0 | xargs -0 -r %{__gzip} -9nf; \
		fi; \
	done; \
	if [ -d "$RPM_BUILD_ROOT%{_infodir}" ]; then \
		echo "Compress info pages: %{_infodir}"; \
		find "$RPM_BUILD_ROOT%{_infodir}" -name '*.bz2' -print0 | xargs -0 -r %{__bzip2} -df; \
		find "$RPM_BUILD_ROOT%{_infodir}" -name '*.gz' -print0 | xargs -0 -r %{__gzip} -dnf; \
		find "$RPM_BUILD_ROOT%{_infodir}" -name '*.info*' -type f -size +%{_min_compress_bytes}c -print0 | xargs -0 -r %{__gzip} -9nf; \
	fi; \
}; __spec_install_post_compress_docs } }

#-----------------------------------------------------------------
# Strip executable binaries and shared object files
#
# Requires: find, awk, strip, cut, xargs
#
# Special macros which affect this process:
#%no_install_post_strip	1		# disable stripping at all
#%_noautostrip			regexp	# exclude files matching (anchored!) regex from stripping
#%_autostripall			regexp	# strip files matching (anchored!) regex using plain strip
#%_autostripunneeded	regexp	# strip files matching (anchored!) regex using strip --strip-unneeded
#%_autostripdebug		regexp	# strip files matching (anchored!) regex using strip --strip-debug
#
%__spec_install_post_strip {%{!?debug: \
%{!?no_install_post_strip:__spec_install_post_strip() { \
%{!?debug:set +x;} \
if [ -d "$RPM_BUILD_ROOT" ]; then \
	if [ -d $RPM_BUILD_ROOT/lib/modules ]; then \
		modulelist=$(find $RPM_BUILD_ROOT/lib/modules \( -name '*.o' -o -name '*.ko' \) -type f -print); \
		if [ "$modulelist" ]; then \
			modulecount=$(echo "$modulelist" | wc -l); \
			printf "Stripping %d kernel modules..." $modulecount; \
			echo "$modulelist" | xargs -l512 chmod u+w; \
			echo "$modulelist" | xargs -l512 %{__strip} -g --remove-section=.comment --remove-section=.note.GNU-stack; \
			echo "DONE"; \
		fi; \
	fi; \
	filelist=$(find $RPM_BUILD_ROOT -type f ! -regex ".*/usr/lib[x0-9]*/debug/.*\.debug" ! -regex ".*/usr/lib[x0-9]*.*/guile/.*\.go" ! -regex ".*/lib/modules/.*" ! -regex ".*%{_docdir}/.*" ! -regex ".*%{_includedir}/.*" %{?_noautostrip:! -regex "%{_noautostrip}"} %{?_autostripall:! -regex "%{_autostripall}"} %{?_autostripunneeded:! -regex "%{_autostripunneeded}"} %{?_autostripdebug:! -regex "%{_autostripdebug}"}); \
	if [ -n "$filelist" ]; then \
		filetypes=`echo "$filelist" | xargs -r -d'\\n' file`; \
		elfexelist=`echo "$filetypes" | awk -F: '/ELF.*executable/ {print $1}'`; \
		elfsharedlist=`echo "$filetypes" | awk -F: '/LF.*shared object/ {print $1}'`; \
		archiveslist=`echo "$filetypes" | awk -F: '/current ar archive/ {print $1}'`; \
		if [ -n "$elfexelist" ]; then \
			printf "Stripping %d ELF executables..." $(echo "$elfexelist" | wc -l); \
			echo "$elfexelist" | xargs -r -d'\n' chmod u+w; \
			echo "$elfexelist" | xargs -r -d'\n' %{__strip} --remove-section=.note --remove-section=.comment; \
			echo "DONE"; \
		fi; \
		if [ -n "$elfsharedlist" ]; then \
			printf "Stripping %d ELF shared libraries..." $(echo "$elfsharedlist" | wc -l); \
			echo "$elfsharedlist" | xargs -r -d'\n' chmod u+w; \
			echo "$elfsharedlist" | xargs -r -d'\n' %{__strip} --strip-unneeded --remove-section=.note --remove-section=.comment; \
			echo "DONE"; \
		fi; \
		if [ -n "$archiveslist" ]; then \
			printf "Stripping %d ar archives..." $(echo "$archiveslist" | wc -l); \
			echo "$archiveslist" | xargs -r -d'\n' chmod u+w; \
			echo "$archiveslist" | xargs -r -d'\n' %{__strip} --strip-debug --remove-section=.note --remove-section=.comment; \
			echo "DONE"; \
		fi; \
	fi; \
    filelist_all=%{?_autostripall:$(find $RPM_BUILD_ROOT -type f -regex "%{_autostripall}")}; \
    filelist_unneeded=%{?_autostripunneeded:$(find $RPM_BUILD_ROOT -type f -regex "%{_autostripunneeded}")}; \
    filelist_debug=%{?_autostripdebug:$(find $RPM_BUILD_ROOT -type f -regex "%{_autostripdebug}")}; \
	if [ -n "$filelist_all" ]; then \
		printf "Stripping everything from %d additional files..." $(echo "$filelist_all" | wc -l); \
		chmod u+w $filelist_all; \
		%{__strip} --remove-section=.note --remove-section=.comment $filelist_all; \
		echo "DONE"; \
	fi; \
	if [ -n "$filelist_unneeded" ]; then \
		printf "Stripping unneeded from %d additional files..." $(echo "$filelist_unneeded" | wc -l); \
		chmod u+w $filelist_unneeded; \
		%{__strip} --strip-unneeded --remove-section=.note --remove-section=.comment $filelist_unneeded; \
		echo "DONE"; \
	fi; \
	if [ -n "$filelist_debug" ]; then \
		printf "Stripping debuginfo from %d additional files..." $(echo "$filelist_debug" | wc -l); \
		chmod u+w $filelist_debug; \
		%{__strip} --strip-debug --remove-section=.note --remove-section=.comment $filelist_debug; \
		echo "DONE"; \
	fi; \
fi; }; __spec_install_post_strip } } }

#-----------------------------------------------------------------
# remove all RPATH/RUNPATH from executable binaries and shared object files
#
# Requires: find, awk, cut, xargs, chrpath, uname
#
# Special macros which affect this process
#%no_install_post_chrpath	1	# disable chrpath at all
#%_noautochrpath	regex		# exclude files matching (anchored!) regex from chrpath
#
%__spec_install_post_chrpath {%{!?debug: \
%{!?no_install_post_chrpath: __spec_install_post_chrpath() { \
%{!?debug:set +x;} \
if [ -d "$RPM_BUILD_ROOT" ]; then \
	files=`find $RPM_BUILD_ROOT -type f ! -regex ".*ld-[0-9.]*so.*" ! -regex ".*/usr/lib[0-9]*/debug/.*" ! -regex ".*/lib/modules/.*" ! -regex ".*%{_docdir}/.*" ! -regex ".*%{_includedir}/.*" %{?_noautochrpath:! -regex "%{_noautochrpath}"}`; \
	if [ -n "$files" ]; then \
		objs=`echo "$files" | xargs -r -d'\\n' file | awk -F: '/ELF.*(executable.*dynamically linked|shared object)/ {print $1}'`; \
	fi; \
	if [ -n "$objs" ]; then \
		printf "Remove RPATH/RUNPATH from %d executable binaries and shared object files.\n" $(echo "$objs" | wc -l); \
		echo "$objs" | \
		while read file; do \
			rpath= ; \
			chmod u+w "$file"; \
			for dir in $(chrpath -l "$file" | awk '/(R|RUN)PATH=/ { gsub(/.*RPATH=/,""); gsub(/.*RUNPATH=/,""); gsub(/:/," "); print $0 }'); do \
					case $dir in \
					'$ORIGIN' ) \
						if [ "$rpath" = "" ] ; then rpath="$dir" ; \
						else rpath="$rpath:$dir" ; fi ; \
						continue ; \
						;; \
					esac ; \
					newdir=$(readlink -m "$dir"); \
					[ ${#newdir} -le ${#dir} ] && dir=$newdir; \
					case $dir in \
					/home/* | /tmp/* | /usr/lib | /usr/lib64 | /lib | /lib64 | /usr/local/lib | /usr/local/lib64 | /usr/X11R6/lib | /usr/X11R6/lib64 ) \
						echo "remove-rpath: $dir in $file"; \
						;; \
					* ) \
						if [ "$rpath" = "" ] ; then rpath="$dir" ; \
						else rpath="$rpath:$dir" ; fi ; \
						;; \
					esac ; \
			done ; \
			if [ "$rpath" = "" ] ; then chrpath -d "$file" > /dev/null ; \
			else chrpath -r "$rpath" "$file" > /dev/null ; fi ; \
		done; \
	fi; \
fi; }; __spec_install_post_chrpath } } }

# vim: "

#-----------------------------------------------------------------
# Find all shared object files with unresolved symbols. Warn
# and terminate if any found (termination can be turned off by define).
#%no_install_post_check_so 1
#%skip_post_check_so libwithunresolvedok.so.*
#
# NOTE: define skip_post_check_so only if such library really requires
#       unresolved symbols and always leave a comment why it is required:
#	# executable provides symbols foo, bar for those libraries:
#	%define skip_post_check_so libwithoutfoo.so.* libwithoutbar.so.*
#
%__spec_install_post_check_so { \
__spec_install_post_check_so() { \
%{!?debug:set +x;} \
	fail=0; \
	printf "Searching for shared objects with unresolved symbols..."; \
	for f in $(find $RPM_BUILD_ROOT -type f -name '*.so.*' -print); do \
		LC_ALL=C objdump -T $f 2> /dev/null | LC_ALL=C awk -v "file=$f" 'BEGIN { found=0; skip["program_name"]=1; skip["_ZSt15__once_callable"]=1; skip["_ZSt11__once_call"]=1; symbols = "" } /^[0-9a-z]+ +D +\*UND\*/ { if ($NF in skip) { next; }; found = 1; symbols = symbols "\n\t" $NF } END { if (found) { print "\nUnresolved symbols found in: " file symbols; %{?skip_post_check_so:split("%{skip_post_check_so}", R); for (i=1; i in R; i++) { if (file ~ "(^|/)" R[i] "$") { print "Library marked with skip_post_check_so, ignoring errors.\n"; exit(0); } } } exit(1); } } ' || fail=1 ; \
	done ; \
	echo " DONE"; \
	%{!?no_install_post_check_so:return $fail;} \
}; __spec_install_post_check_so }}

#-----------------------------------------------------------------
# Find all ELF files with executable stac. Warn and terminate if any found
# (termination can be turned off by define).
# Details: https://wiki.gentoo.org/wiki/Hardened/GNU_stack_quickstart
#%no_install_post_check_stackexec 1
#%skip_post_check_stackexec libwithexecstackok.so.*
#
# NOTE: define skip_post_check_stackexec only if such program or library
#       really requires executable stack and always leave a comment why
#       it is required:
#	# Programs full of nested functions that cannot be fixed
#	%define skip_post_check_execstack /bin/foo libwithexecstack.so.*
#
%__spec_install_post_check_execstack { \
__spec_install_post_check_execstack() { \
%{!?debug:set +x;} \
	fail=0; \
	printf "Searching for ELF programs with executable stack..."; \
	for f in $(find $RPM_BUILD_ROOT -type f -print) ; do \
		LC_ALL=C readelf -lW $f 2>/dev/null | \
		LC_ALL=C awk -v "file=$f" 'BEGIN { found=0; } /GNU_STACK/ { if ($7 ~ "E") { found=1 } } END { if (found) { print "\nExecutable stack found in: " file; %{?skip_post_check_execstack:split("%{skip_post_check_execstack}", R); for (i=1; i in R; i++) { if (file ~ "(^|/)" R[i] "$") { print "File marked with skip_post_check_execstack, ignoring errors.\n"; exit(0); } } } exit(1); } }' || fail=1 ; \
	done ; \
	echo " DONE"; \
	%{!?no_install_post_check_execstack:return $fail;} \
}; __spec_install_post_check_execstack }}

#-----------------------------------------------------------------
# Verify that for each directory under /var/run package contains
# tmpfiles.d configuration. Warn and terminate build if config is
# missing.
#
#%no_install_post_check_tmpfiles 1
#
%__spec_install_post_check_tmpfiles { \
__spec_install_post_check_tmpfiles() { \
%{!?debug:set +x;} \
	fail=0; \
	echo "Checking /var/run <-> tmpfiles.d completeness..."; \
	for d in $RPM_BUILD_ROOT/var/run/*; do \
		[ -d "$d" ] || continue; \
		d=${d##$RPM_BUILD_ROOT}; \
		if ! grep -qsF "$d" $RPM_BUILD_ROOT/usr/lib/tmpfiles.d/*.conf $RPM_BUILD_ROOT/etc/tmpfiles.d/*.conf; then\
			echo "No tmpfiles configuration for '$d'";\
			fail=1 ; \
		fi \
	done ; \
	echo " DONE"; \
	%{!?no_install_post_check_tmpfiles:return $fail;} \
}; __spec_install_post_check_tmpfiles }}

#-----------------------------------------------------------------
# Verify that scripts have reasonable shebangs
# Test spec: see "test/spec_install_post_check_shebangs" branch on packages/test.spec
#
#%no_install_post_check_shebangs 1
#
%__spec_install_post_check_shebangs { \
__spec_install_post_check_shebangs() { \
%{!?debug:set +x;} \
	echo "Checking script shebangs..."; \
	fail=` \
	find $RPM_BUILD_ROOT -type f -perm -500 -print | { fail=0; while IFS= read -r f; do \
		shebang="$(sed -e'1s/#! *\(.*\)/\1/;t;d;q' "$f")" ; \
		f="${f##$RPM_BUILD_ROOT}"; \
		case "$shebang" in \
			"%{__python}"|"%{__python3}"|"%{__python} "*|"%{__python3} "* \
			|"/usr/bin/python%{py_ver}"|"/usr/bin/python%{py_ver} "* \
			|"/usr/bin/python%{py3_ver}"|"/usr/bin/python%{py3_ver} "*) \
				;; \
			"/usr/bin/env python"*|"/usr/bin/python"|"/usr/bin/python "*) \
				echo "$f starts with '#!$shebang', should be '#!%{__python}' or '#!%{__python3}'" >&2;\
				fail=1 ; \
				;; \
			"/usr/bin/env "*) \
				echo "$f starts with '#!$shebang', should be explicit interpreter path" >&2;\
				fail=1 ; \
				;; \
			*) ;;\
		esac ; \
	done ; \
	echo "$fail" ; \
	}`; \
	echo " DONE" ; \
        %{!?no_install_post_check_shebangs:return $fail;} \
}; __spec_install_post_check_shebangs }}

# Remove common Perl files we don't package
%__spec_install_post_perl_clean {\
%{!?no_install_post_perl_clean: \
%{?pdir:rm -f $RPM_BUILD_ROOT{%{perl_archlib}/perllocal.pod,%{perl_vendorarch}/auto/%{pdir}%{?pnam:/%(echo %{pnam} | tr - /)}/.packlist}} \
} }

# Helpers to specify SONAME depdendencies, e.g.:
#   Requires: %{_soname_prov libfoo.so.1}
#   Requires: %{_soname_prov libfoo.so.1(SOME_SYMVER)}
#
# BuildRequires:	rpmbuild(macros) >= 1.721
#
%_soname_tag %(echo %{_lib} | sed -e 's/^lib//' -e 's/^\\(.\\+\\)$/(\\1bit)/')
%_soname_prov() %(echo "%{1}()%{_soname_tag}" | sed -e 's/^\\([^(]*([^)]\\+)\\)()%{_soname_tag}$/\\1%{_soname_tag}/;s/()$//')

#-----------------------------------------------------------------
# Update GConf2 schemas
#
# Requires: GConf2
#
%gconf_schema_install() \
	umask 022; \
	GCONF_CONFIG_SOURCE="xml:readwrite:/etc/gconf/gconf.xml.defaults" \\\
	/usr/bin/gconftool-2 --makefile-install-rule /etc/gconf/schemas/%{?1}%{!?1:*.schemas} > /dev/null; \
%{nil}

%gconf_schema_uninstall() \
if [ $1 = 0 -a -x /usr/bin/gconftool-2 ]; then \
	umask 022; \
	GCONF_CONFIG_SOURCE="xml:readwrite:/etc/gconf/gconf.xml.defaults" \\\
	/usr/bin/gconftool-2 --makefile-uninstall-rule /etc/gconf/schemas/%{?1} > /dev/null \
fi; \
%{nil}

#-----------------------------------------------------------------
# Update desktop MIME database
# requires: desktop-file-utils
%update_desktop_database() {{ \
	umask 022; \
	/usr/bin/update-desktop-database -q; \
};} \
%{nil}

%update_desktop_database_post %update_desktop_database

%update_desktop_database_postun() {{ \
if [ "$1" = "0" ]; then \
	%update_desktop_database \
fi; \
};} \
%{nil}

#-----------------------------------------------------------------
# Update shared MIME info database
# requires: shared-mime-info
# Note:	https://bugs.freedesktop.org/show_bug.cgi?id=70366#c19
#	https://bugzilla.redhat.com/show_bug.cgi?id=1052173
# TODO:	if you want this running with fdatasync(), make sure it's:
#	1. announcing ~minute delay by echoing appropriate message,
#	2. running only once after rpm transaction.
#
%update_mime_database() {{ \
	umask 022; \
	PKGSYSTEM_ENABLE_FSYNC=0 \
	/usr/bin/update-mime-database %{_datadir}/mime; \
};} \
%{nil}

#-----------------------------------------------------------------
# Update icon cache
# BuildRequires:	rpmbuild(macros) >= 1.596
# Requires:		hicolor-icon-theme
#
%update_icon_cache() {{ \
	%{!?1:%{error:%{0}: Required theme name missing}} \
	if [ -x /usr/bin/gtk-update-icon-cache ]; then \
		umask 022; \
		touch --no-create %{_iconsdir}/%1; \
		/usr/bin/gtk-update-icon-cache -qf %{_iconsdir}/%1; \
	fi; \
};} \
%{nil}

#-----------------------------------------------------------------
# Update scrollkeeper database
# requires: scrollkeeper
#
%scrollkeeper_update_post() \
	/usr/bin/scrollkeeper-update -q; \
%{nil}

%scrollkeeper_update_postun() \
if [ "$1" = "0" ]; then \
	/usr/bin/scrollkeeper-update -q; \
fi; \
%{nil}

#-----------------------------------------------------------------
# Compile GSettings schemas
# requires: glib2 >= 1:2.26.0
#
%glib_compile_schemas() {{ \
	umask 022; \
	/usr/bin/glib-compile-schemas %{_datadir}/glib-2.0/schemas; \
};} \
%{nil}

# BuildRequires:	rpmbuild(macros) >= 1.751
# Requires(post,postun):	/usr/bin/texhash	# if you want to ensure cache is updated
%texhash() {{ \
	umask 022; \
	/usr/bin/texhash >&2; \
};} \
%{nil}

#-----------------------------------------------------------------
# post %install sequence:
# - autodeps exceptions
# - compress all man and info pages,
# - strip all ELF executables and ELF shared objects if not %debug.
# - compress kernel modules if any

###################################################################
# Requires/Provides automation
# exceptions system by Jacek Konieczny <jajcus@pld-linux.org>
#
%__noautoreqfiles	%(sed -e s'/#.*//' /etc/rpm/noautoreqfiles)%{?_noautoreqfiles: %{_noautoreqfiles}}
%__noautoprovfiles	%(sed -e s'/#.*//' /etc/rpm/noautoprovfiles)%{?_noautoprovfiles: %{_noautoprovfiles}}
%__noautoprov		%(sed -e s'/#.*//' /etc/rpm/noautoprov) \
	%{?_noautoprov: %{_noautoprov}} \
	%{?_noautoprov_java: %{__noauto_regexp_helper -p java %{_noautoprov_java}}} \
	%{?_noautoprov_mono: %{__noauto_regexp_helper -p mono %{_noautoprov_mono}}} \
	%{?_noautoprov_pear: %{__noauto_regexp_helper -p pear %{_noautoprov_pear}}} \
	%{?_noautoprov_perl: %{__noauto_regexp_helper -p perl %{_noautoprov_perl}}} \
	%{?_noautoprov_pyegg: %{__noauto_regexp_helper -p pythonegg %{_noautoprov_pyegg}}} \
	%{?_noautoprov_py3egg: %{__noauto_regexp_helper -p python3egg %{_noautoprov_py3egg}}} \
	%{nil}
%__noautoreq		%(sed -e s'/#.*//' /etc/rpm/noautoreq) \
	%{?_noautoreq: %{_noautoreq}} \
	%{?_noautoreqdep: %{_noautoreqdep}} \
	%{?_noautoreq_java: %{__noauto_regexp_helper -p java %{_noautoreq_java}}} \
	%{?_noautoreq_mono: %{__noauto_regexp_helper -p mono %{_noautoreq_mono}}} \
	%{?_noautoreq_pear: %{__noauto_regexp_helper -p pear %{_noautoreq_pear}}} \
	%{?_noautoreq_perl: %{__noauto_regexp_helper -p perl %{_noautoreq_perl}}} \
	%{?_noautoreq_pyegg: %{__noauto_regexp_helper -p pythonegg %{_noautoreq_pyegg}}} \
	%{?_noautoreq_py3egg: %{__noauto_regexp_helper -p python3egg %{_noautoreq_py3egg}}} \
	%{nil}

%__noautodep_helper() %(awk -v x="%*" 'BEGIN {
	RS = "\n([ \t]+\n)+";
	FS = " ";
	split(x, F);
	if (length(F) > 0) {
		printf("(");
		for (i=1; i<=length(F); i++) {
			s = F[i];
			sub(/#.*/, "z&z", s);
			if (s ~ /^$/) { continue; };
			printf(s);
			if (i != length(F)) { printf("|"); };
		};
		printf(")");
	}
}')
%__requires_exclude_from	%{__noautodep_helper %{__noautoreqfiles}}%{nil}
%__provides_exclude_from	%{__noautodep_helper %{__noautoprovfiles}}%{nil}
%__requires_exclude			%{__noautodep_helper %{__noautoreq}}%{nil}
%__provides_exclude			%{__noautodep_helper %{__noautoprov}}%{nil}

# helper for wrapping _noautoreq between perl() or pear()
# Author: Elan Ruusamäe <glen@pld-linux.org>
# Usage:
# BuildRequires:	rpmbuild(macros) >= 1.654
# %define _noautoreq_pear Excluded.php PEAR/Something.php
# %define _noautoreq_perl Apache::.*
# BuildRequires:	rpmbuild(macros) >= 1.672
# %define _noautoreq_java ClassDataVersion
# BuildRequires:	rpmbuild(macros) >= 1.709
# %define _noautoreq_pyegg argparse
# %define _noautoreq_py3egg backports.ssl-match-hostname ipaddress
# BuildRequires:	rpmbuild(macros) >= 1.730
# %define _noautoreq_mono Gendarme.Framework
# BuildRequires:	rpmbuild(macros) >= 1.737
# %define _noautoprov_java Class
# %define _noautoprov_mono Excluded.Provide
# %define _noautoprov_pear Excluded.php
# %define _noautoprov_perl Excluded::Module
# %define _noautoprov_pyegg excluded
# %define _noautoprov_py3egg excluded3
#
%__noauto_regexp_helper(p:) %(echo "%*" | awk 'BEGIN{RS=" "}{printf("%{-p*}%{__qchar}(%%s%{__qchar}) ", $1)}')
# detect quote character runtime
%__qchar_4 \\\\%{nil}
%__qchar_5 \\\\\\%{nil}
%__qchar %{expand:%%global __qchar %%__qchar_%(echo %{_rpmversion} | cut -c1)}%__qchar

#%_noautocompressdoc	%{nil}
#
%_missing_doc_files_terminate_build	1%{nil}
%_unpackaged_files_terminate_build	%{nil}

# node.js libdir
# Requirements:
# BuildRequires: rpmbuild(macros) >= 1.634
%nodejs_libdir		/usr/lib/node_modules

# bash-completion 2.0 completions dir
# Requirements:
# BuildRequires:	rpmbuild(macros) >= 1.673
# Requires:	bash-completion >= 2.0
%bash_compdir		/usr/share/bash-completion/completions

# fish completions dir
# Requirements:
# BuildRequires:	rpmbuild(macros) >= 1.720
%fish_compdir		/usr/share/fish/vendor_completions.d

# zsh completions dir
# Requirements:
# BuildRequires:	rpmbuild(macros) >= 1.719
%zsh_compdir		/usr/share/zsh/site-functions

# depmod macro
%depmod() { \
umask 022; \
if [ -e /boot/System.map-%1 ]; then \
	/sbin/depmod -a -F /boot/System.map-%1 %1; \
else \
	if [ -e /boot/System.map ]; then \
		/sbin/depmod -a -F /boot/System.map %1; \
	else \
		/sbin/depmod -a %1; \
	fi \
fi; \
}

# user/group checking macros
#
# Usage:
#	%userremove myuser
#
%userremove	/usr/lib/rpm/user_group.sh user del
%groupremove	/usr/lib/rpm/user_group.sh group del
#
# Usage:
#	if %usertestrm myuser; then
#		/usr/sbin/userdel -r myuser
# Note:
#	use these macros only if you need to call userdel/groupdel with
#	a non-standard option or take an extra action; otherwise use the
#	%userremove/%groupremove macros
#
%usertestrm	/usr/lib/rpm/user_group.sh user testrm
%grouptestrm	/usr/lib/rpm/user_group.sh group testrm
# user group membership management macros
#
# Usage:
#	%addusertogroup [-q] myuser agroup
#
#  -q if user or group don't exist, don't make big noise of it (MISSINGOK behaviour)
#
# Requirements:
# BuildRequires:	rpmbuild(macros) >= 1.515
%addusertogroup(q)	quiet=%{-q:1} /usr/lib/rpm/user_group.sh user addtogroup %*; \
%{nil}

# banner support (useful in {pre,post}{,un} and triggers)
#
# Usage:
#	%banner name [-a] [-e] [-n] [-tn] [-o] <<EOF
# the banner text, the banner text
# the banner text, and following line
#EOF
# You can use any form of here-document, <<'EOF' <<-EOT will do.
# NOTE: if your use "<<-EOF", then You can actually indent inside here-document.
#
# -a	- append to the banner
# -e	- send to stderr instead of stdout
# -n	- don't show banner (overrides -t)
# -t	- show only, if RPM_SCRIPTVERBOSITY >= n; default n=5
# -o	- show only once, i.e when package is installed for the first time
#
# Tests:
# (rpm -E '%banner -e banner <<EOF'; echo -e 'hi\nEOF') > m; sh -x m
# (rpm -E '%banner -o -e banner <<EOF'; echo -e 'hi\nEOF') > m; sh -x m
# (rpm -E '%banner -o -e banner <<EOF'; echo -e 'hi\nEOF') > m; sh -x m 1
# rpm -E 'date | %banner -e banner' > m; sh -x m
# rpm -E 'date | %banner -o -e banner' > m; sh -x m
#
%banner(aenot:) %{-o:([ "$1" != 1 ] ||} ( \
RPM_SCRIPTVERBOSITY=5 \
[ -r /etc/sysconfig/rpm ] && . /etc/sysconfig/rpm \
if [ -x /usr/bin/banner.sh ]; then \
	CMD="/usr/bin/banner.sh %{-e:--stderr} %{!-n:$([ $RPM_SCRIPTVERBOSITY -ge %{-t:%{-t*}}%{!-t:5} ] && echo -s)} %{!-a:-m}%{-a:-M} %1" \
else \
	CMD="cat%{-e: >&2}" \
fi \
eval $CMD %{?2:%2}%{?3: %3})%{-o:)} \
%{nil}

# useradd/groupadd macros
# Author: Elan Ruusamäe <glen@pld-linux.org>
#
# Usage:
#   %useradd [-P package] [-u uid] [-d home_dir] [-s shell] [-c comment]
#   [-g initial_group] [-G group[,...]] login
#
#  -u uid. REQUIRED
#  -g gid/group. REQUIRED
#  -s defaults to /bin/false
#  -d defaults to /usr/share/empty
#  -c No default
#  -r is accepted but ignored (it's always set)
#  -k skeleton dir. defaults to /usr/share/empty
# rpm specific flags
#  -P package name. defaults to %{name}
#
%useradd(c:d:e:f:g:G:Mmk:op:s:u:rP:) \
%{!-u:%{error:useradd: Required argument -u missing}} \
%{!-g:%{error:useradd: Required argument -g missing}} \
%{!?1:%{error:useradd: Required parameter login missing}} \
if [ -n "`/bin/id -u %{expand:%{%{#}}} 2>/dev/null`" ]; then \
	if [ "`/bin/id -u %{expand:%{%{#}}}`" != "%{-u*}" ]; then \
		echo "Error: user %{expand:%{%{#}}} doesn't have uid=%{-u*}. Correct this before installing %{-P*}%{!?-P:%{name}}." 1>&2 \
		exit 1 \
	fi \
else \
	echo "Adding user %{expand:%{%{#}}} UID=%{-u*}." \
	/usr/sbin/useradd \\\
		%{-m:-m -k %{-k*}%{!-k:/usr/share/empty}} \\\
		-u %{-u*} \\\
		-r \\\
		-d %{-d*}%{!-d:/usr/share/empty} \\\
		-s %{-s*}%{!-s:/bin/false} \\\
		%{-c:-c "%(set -- %{-c*} %{*}; echo $1)"}\\\
		-g %{-g*} \\\
		%{-M} \\\
		%{-G:-G %{-G*}} \\\
		%{expand:%{%{#}}} 1>&2 || exit $? \
	[ ! -x /usr/sbin/nscd ] || /usr/sbin/nscd -i passwd || : \
fi;
# vim: "

# Usage:
#   %groupadd [-P package] [-g gid] group
#
# -g gid. REQUIRED
#
# Sample:
#   %groupadd -P %{name}-base -g %{gid} %{name}

%groupadd(g:P:rfo)	\
%{!-g:%{error:groupadd: Required argument -g missing}} \
%{!?1:%{error:groupadd: Required parameter group missing}} \
if /usr/bin/getgid %{1} > /dev/null 2>&1; then \
	if [ "`/usr/bin/getgid %{1}`" != "%{-g*}" ]; then \
		echo "Error: group %{1} doesn't have gid=%{-g*}. Correct this before installing %{-P*}%{!?-P:%{name}}." 1>&2 \
		exit 1 \
	fi \
else \
	echo "Adding group %{1} GID=%{-g*}." \
	/usr/sbin/groupadd -g %{-g*} -r %{1} 1>&2 || exit $? \
	[ ! -x /usr/sbin/nscd ] || /usr/sbin/nscd -i group || : \
fi;

# service macro.
# Author: Elan Ruusamäe <glen@pld-linux.org>
#
# calls usual service restart on package %post, but skips the restart if
# administrator has disabled automatic service restarts in either global
# /etc/sysconfig/rpm or per service /etc/sysconfig/SERVICE file.
# NOTE: systemd_booted machines do not print
#		Run "{command}" to restart {service}.
# message for packages without native systemd unit (not here, no %systemd_post).
#
# Usage:
#   %service [-q] [-n] SERVICE ACTION ["SERVICE NICE DESCRIPTION"]
#
#  -q be silent when service isn't started (for scriplets restaring other package's services)
#  -n NOOP mode, do not actually restart service
#
# Requirements:
# BuildRequires:	rpmbuild(macros) >= 1.268
# Requires:	rc-scripts
# -n option:
# BuildRequires:	rpmbuild(macros) >= 1.450
%service(qn) {{%(export noop=%{-n:1} quiet=%{-q:1} RPM_BUILD_ROOT=%{buildroot}; /usr/lib/rpm/service_generator.sh %{*}) };}

%env_update [ ! -x /sbin/env-update ] || /sbin/env-update -u || :

# patchset macros
# generate SourceX urls from range START STOP
# Format can be SINGLE format char of %e, %f, %g, see seq(1)
# The sources start from 10000
#
# Author: Elan Ruusamäe <glen@pld-linux.org>
#
# Usage:
#   %patchset_source -f <seq(1) format> <start> [<end>]
#   %patchset_patch <start> [<end>]
# If <end> is omited, it is assumed to be <start>.
#
# For example in preamble:
#  %patchset_source -f ftp://ftp.vim.org/pub/editors/vim/patches/7.0/7.0.%03g 33 44
# and in %prep:
#  %patchset_patch 33 44
#
# Using sources list:
#   BuildRequires:	rpmbuild(macros) >= 1.426
#   %patchset_source -f <url> -s <filelist>
#   %patchset_patch -s <filelist>
# For example (ncurses):
#   BuildRequires:	rpmbuild(macros) >= 1.683
#   %patchset_source -f ftp://dickey.his.com/ncurses/%{basever}/ -s sources
#   %patchset_patch -s sources -p1
#

%patchset_source(f:b:s:) %(
	base=%{-b*}%{!-b*:10000}
%{-s:
	baseurl='%{-f*}'
	filelist='%{-s*}'
	i=$base
	while read checksum file; do
		printf "Patch%d: %s%s\\n" $i "$baseurl" "$file"
		i=$((i+1))
	done < $filelist
}
%{!-s:
	start=$(expr $base + %1);
	end=$(expr $base + %{?2}%{!?2:%{1}});
	# we need to call seq twice as it doesn't allow two formats
	seq -f 'Patch%g:' $start $end > %{_tmppath}/__ps1;
	seq -f '%{-f*}' %1 %{?2}%{!?2:%{1}} > %{_tmppath}/__ps2;
	paste %{_tmppath}/__ps{1,2};
	rm -f %{_tmppath}/__ps{1,2};
}
) \
%{nil}

# apply sources from %patchset_source
# -p specify -pX for %patch line
# -b base offset: defaults to 10000
# -s filelist to read files from
%patchset_patch(f:p:b:s:) %(
	base=%{-b*}%{!-b*:10000}
	patchlevel=%{-p*:-p%{-p*}}
%{-s:
	filelist='%{-s*}'
	i=$base
	while read checksum file; do
		printf "patch%d %s\\n" $i "$patchlevel" | sed -e s,^,%%,
		i=$((i+1))
	done < $filelist
}
%{!-s:
	start=$(expr $base + %1);
	end=$(expr $base + %{?2}%{!?2:%{1}});
	echo ": patchset_patch %1%{?2: to %2}";
	seq -f "patch%g $patchlevel" $start $end | sed -e s,^,%%,;
}
) \
%{nil}

# return EXPANDED source url N from current spec
%sourceurl(n:) %(test "$IN_RPM" = 1 && exit 1; export IN_RPM=1; rpmbuild --nodigest --nosignature --nobuild -D "prep %%dump" %{_specdir}/%{name}.spec 2>&1 | awk '$2 ~ /^SOURCEURL%{-n*}/ {print $3}')

# Helper for LUA.
# split string separated by space into quoted list
#
# Author: Elan Ruusamäe <glen@pld-linux.org>
#
# %__lua_split /bin/sh /bin/pdksh -> "/bin/sh", "/bin/pdksh"
%__lua_split() %(echo "%*" | awk '{for (i=1;i<=NF;i++) printf("\\"%%s\\"%%s", $i, i == NF ? "" : ", ")}')

# adjust /etc/shells by adding and removing shells from there
# Author: Elan Ruusamäe <glen@pld-linux.org>
#
# Usage:
#   %post	-p <lua>
#   %lua_add_etc_shells /bin/sh /bin/pdksh
#
#   %preun	-p <lua>
#   if arg[2] == 0 then
#       %lua_remove_etc_shells /bin/bash /bin/rbash
#   end
#
# Requirements:
# BuildRequires:	rpmbuild(macros) >= 1.462
#

%lua_add_etc_shells() \
t = {}\
f = io.open("/etc/shells", "r")\
if f then\
	for l in f:lines() do t[l]=l; end\
	f:close()\
end\
for _, s in ipairs({%{expand:%%__lua_split %*}}) do\
	if not t[s] then\
		print("Adding "..s.." to /etc/shells")\
		f = io.open("/etc/shells", "a")\
		if f then\
			f:write(s.."\\n")\
			f:close()\
		end\
	end\
end\
%{nil}

%lua_remove_etc_shells() \
t = {}\
f = io.open("/etc/shells", "r")\
if f then\
	for l in f:lines() do t[l]=l; end\
	f:close()\
end\
for _, l in pairs({%{expand:%%__lua_split %*}}) do\
	print("Removing "..l.." from /etc/shells")\
	t[l] = nil\
end\
s=""\
for _, l in pairs(t) do\
	s=s..l.."\\n"\
end\
f = io.open("/etc/shells", "w")\
if f then\
	f:write(s)\
	f:close()\
end\
%{nil}

# Backwards compat. Use of %lua_ prefixed macros is preferred as these are cleaner to read.
#
# Author: Elan Ruusamäe <glen@pld-linux.org>
#
# Usage:
#   %post	-p %add_etc_shells -p /bin/sh /bin/pdksh
#   %preun	-p %remove_etc_shells -p /bin/sh /bin/pdksh
#
#  -p (optional) -- specifies that result is embeded %post script (prepends <lua> as first line)
#
# Requirements:
# BuildRequires:	rpmbuild(macros) >= 1.429
#
%add_etc_shells(p) %{-p:<lua>}\
%{expand:%%lua_add_etc_shells %*}\
%{nil}

%remove_etc_shells(p) %{-p:<lua>}\
%{-p:if arg[2] == 0 then}\
%{expand:%%lua_remove_etc_shells %*}\
%{-p:end} \
%{nil}

# Undos files
#
# Author: Paweł Zuzelski <pawelz@pld-linux.org>
# Author: Elan Ruusamäe <glen@pld-linux.org>
#
# Usage:
#   %undos list_of_files
#   %undos -f EXT[,EXT]
#   %undos -i -f EXT[,EXT]
#
#  -f EXT[,EXT] - find(1) files by extensions
#  -i - case insensitive file search
#
# Example:
#   Un-DOS all *.js, *.css files
#   %undos -f js,css
#   Un-DOS all *.js, *.JS files
#   %undos -f js -i
#   undos all Makefiles
#   %{__find} -name Makefile | xargs %undos
#
# Requirements:
# BuildRequires:	sed >= 4.0
# BuildRequires:	rpmbuild(macros) >= 1.674

# NB: make sure this macro stays on one line
# NB: make sure it includes newline escape
%undos(f:i)	%{-f:%{__find} -type f -regextype posix-extended -%{-i:i}regex '^.+\\.(%(echo %{-f*} | tr ',' '|'))$' -print0 | xargs -0} %{__sed} -i -e 's,\\r$,,' %* \
%{nil}

#-----------------------------------------------------------------
# Update hardware database index
#
# Requirements:
# BuildRequires:	rpmbuild(macros) >= 1.691
# Requires:		udev-core >= 1:196

%udev_hwdb_update() \
/sbin/udevadm hwdb --update >/dev/null 2>&1 || : \
%{nil}

# Generate vim help tags file
#
# Requirements:
# BuildRequires:	rpmbuild(macros) >= 1.718
# Requires(post,postun):	/usr/bin/vim
# Requires(post,postun):	vim-rt >= 4:7.4.2054-2
%vim_doc_helptags() \
umask 022; \
/usr/bin/vim -c ':helptags /usr/share/vim/doc' -c ':q' 2>/dev/null \
%{nil}
