# Per-platform rpm configuration file.

%_vendor 		openEuler
%_os			linux
%_target_platform	%{_target_cpu}-%{_vendor}-%{_target_os}%{?_gnu}

#==============================================================================
# ---- configure macros.  note that most of these are inherited
#      from the defaults.
#
%_localstatedir		/var

%_pkgdocdir             %{_docdir}/%{name}
%_docdir_fmt            %%{NAME}

%_fmoddir		%{_libdir}/gfortran/modules

%_enable_debug_packages 1
#%_include_minidebuginfo 1
%_include_gdb_index     1
%_debugsource_packages  1
#%_debuginfo_subpackages 1

%_build_id_links none

# GCC toolchain
%__cc_gcc gcc
%__cxx_gcc g++
%__cpp_gcc gcc -E
 
# Clang toolchain
%__cc_clang clang
%__cxx_clang clang++
%__cpp_clang clang-cpp
 
# Default to the GCC toolchain
#
# It is enough to override `toolchain` macro and all relevant macro for C/C++
# compilers will be switched. Either in the spec or in the command-line.
#
#     %global toolchain clang
#
# or:
#
#     rpmbuild -D "toolchain clang" …
#
# Inside a spec file it is also possible to determine which toolchain is in use
# by testing the same macro. For example:
#
#     %if "%{toolchain}" == "gcc"
#     BuildRequires: gcc
#     %endif
#
# or:
#
#     %if "%{toolchain}" == "clang"
#     BuildRequires: clang compiler-rt
#     %endif
#
%toolchain gcc
 
%__cc %{expand:%%{__cc_%{toolchain}}}
%__cxx %{expand:%%{__cxx_%{toolchain}}}
%__cpp %{expand:%%{__cpp_%{toolchain}}}

#==============================================================================
# ---- compiler flags.

%build_cflags %{optflags}
%build_cxxflags %{optflags} -fexceptions
%build_fflags %{optflags} -fexceptions -I%{_fmoddir}

# When clang is used as a linker driver, it does not auto-detect the LTO
# bytecode and neither does bfd, so we need to explicitly pass the -flto
# flag when linking.
%_clang_extra_ldflags %{?_lto_cflags}

%build_ldflags -Wl,-z,relro %{_ld_as_needed_flags} %{_ld_symbols_flags} %{_hardened_ldflags} %[ "%{toolchain}" == "clang" ? "%{?_clang_extra_ldflags}" : "" ]

%set_build_cc \
  CC=%{__cc}; export CC ; \
  CXX=%{__cxx}; export CXX ; \
  CCC="${CCC:-%{__cxx}}" ; export CCC

%set_build_flags \
  %[ "%{toolchain}" == "gcc" ? "" : "%{set_build_cc};" ] \
  CFLAGS="${CFLAGS:-%{build_cflags}}" ; export CFLAGS ; \
  CXXFLAGS="${CXXFLAGS:-%{build_cxxflags}}" ; export CXXFLAGS ; \
  FFLAGS="${FFLAGS:-%{build_fflags}}" ; export FFLAGS ; \
  FCFLAGS="${FCFLAGS:-%{build_fflags}}" ; export FCFLAGS ; \
  LDFLAGS="${LDFLAGS:-%{build_ldflags}}" ; export LDFLAGS

# Automatically use set_build_flags macro for build, check, and
# install phases.
# Use "%undefine _auto_set_build_flags" to disable"
# Automatically use set_build_cc macro for build, check, and
# install phases.
# Use "%undefine _auto_set_build_cc" to disable"
%_auto_set_build_cc %["%{toolchain}" == "gcc" ? 0 : 1]
%_auto_set_build_flags 0

%__spec_build_pre %{___build_pre} \
  %[0%{?_auto_set_build_cc} ? "%{set_build_cc}" : ""] \
  %[0%{?_auto_set_build_flags} ? "%{set_build_flags}" : ""]
%__spec_check_pre %{___build_pre} \
  %[0%{?_auto_set_build_cc} ? "%{set_build_cc}" : ""] \
  %[0%{?_auto_set_build_flags} ? "%{set_build_flags}" : ""]

# Internal-only.  Do not use.  Expand a variable and strip the flags
# not suitable to extension builders.
%__extension_strip_flags() %{lua:
--the only argument to this macro is the "name" of the flags we strip (e.g. cflags, ldflags, etc.)
local name = rpm.expand("%{1}")
--store all the individual flags in a variable as a continuous string
local flags = rpm.expand("%{build_" .. name .. "}")
--create an empty table for the minimal set of flags we wanna preserve
local stripped_flags = { }
--iterate over the individual flags and store the ones we want in the table as unique keys
for flag in flags:gmatch("%S+") do
  if flag:find("^%-fexceptions") or flag:find("^%-fcf%-protection") then
    stripped_flags[flag] = true end
  end
--print out the finalized set of flags for use by the extension builders
for k,_ in pairs(stripped_flags) do print(k .. " ") end
}

# Variants of CFLAGS, CXXFLAGS, FFLAGS, LDFLAGS for use within
# extension builders.
%extension_cflags %{__extension_strip_flags cflags}
%extension_cxxflags %{__extension_strip_flags cxxflags}
%extension_fflags %{__extension_strip_flags fflags}
%extension_ldflags %{__extension_strip_flags ldflags}

#For backwards compatibility only.
%__global_cflags %{build_cflags}
%__global_cxxflags %{build_cxxflags}
%__global_fflags %{build_fflags}
%__global_fcflags %{build_fflags}
%__global_ldflags %{build_ldflags}

#==============================================================================
# ---- configure and makeinstall.
%_configure_gnuconfig_hack	1
%_configure_libtool_hardening_hack	1

#update config.guess and config.sub
%_update_config_guess \
  [ "%_configure_gnuconfig_hack" = 1 ] && for i in $(find . -name config.guess) ; do \
      [ -f /usr/lib/rpm/%{_vendor}/$(basename $i) ] && \
      %{__rm} -f $i && \
      %{__cp} -fv /usr/lib/rpm/%{_vendor}/$(basename $i) $i ; \
  done ;

%_update_config_sub \
  [ "%_configure_gnuconfig_hack" = 1 ] && for i in $(find . -name config.sub) ; do \
      [ -f /usr/lib/rpm/%{_vendor}/$(basename $i) ] && \
      %{__rm} -f $i && \
      %{__cp} -fv /usr/lib/rpm/%{_vendor}/$(basename $i) $i ; \
  done ;

# This fixes various easy resolved configure tests that are compromised by LTO.
#
# We use this within the standard %configure macro, but also make it available
# for packages which don't use %configure
#
# The first three are common ways to test for the existence of a function, so
# we ensure the reference to the function is preserved
#
# The fourth are constants used to then try to generate NaNs and other key
# floating point numbers.  We then use those special FP numbers to try and
# raise a SIGFPE.  By declaring x & y volatile we prevent the optimizers
# from removing the computation
#
# The fifth (and worst) addresses problems with autoconf/libtool's approach
# to extracting symbols from .o files and generating C code.  In an LTO world
# types matter much more closely and you can't have an object in one context
# that is a function definition and a simple scalar variable in another.
# Thankfully HP-UX has always had that restriction and is supported by
# autoconf/libtool.  The insane sed script replaces the "generic" code with
# the HP-UX version.
#
# If we do not make changes, we put the original file back.  This avoids
# unnecessary rebuilds of things that may have dependencies on the configure
# files.
#
%_fix_broken_configure_for_lto \
  for file in $(find . -type f -name configure -print); do \
    %{__sed} -r --in-place=.backup 's/^char \\(\\*f\\) \\(\\) = /__attribute__ ((used)) char (*f) () = /g' $file; \
    diff -u $file.backup $file && mv $file.backup $file \
    %{__sed} -r --in-place=.backup 's/^char \\(\\*f\\) \\(\\);/__attribute__ ((used)) char (*f) ();/g' $file; \
    diff -u $file.backup $file && mv $file.backup $file \
    %{__sed} -r --in-place=.backup 's/^char \\$2 \\(\\);/__attribute__ ((used)) char \\$2 ();/g' $file; \
    diff -u $file.backup $file && mv $file.backup $file \
    %{__sed} --in-place=.backup '1{$!N;$!N};$!N;s/int x = 1;\\nint y = 0;\\nint z;\\nint nan;/volatile int x = 1; volatile int y = 0; volatile int z, nan;/;P;D' $file; \
    diff -u $file.backup $file && mv $file.backup $file \
    %{__sed} --in-place=.backup 's#^lt_cv_sys_global_symbol_to_cdecl=.*#lt_cv_sys_global_symbol_to_cdecl="sed -n -e '"'"'s/^T .* \\\\(.*\\\\)$/extern int \\\\1();/p'"'"' -e '"'"'s/^$symcode* .* \\\\(.*\\\\)$/extern char \\\\1;/p'"'"'"#' $file; \
    diff -u $file.backup $file && mv $file.backup $file \
  done

%__fix_libtool_from_moving_options_after_libs /usr/lib/rpm/fix-libtool-from-moving-options-after-libs $(dirname %{_configure})

%configure \
  %{set_build_flags}; \
  [ "%{_lto_cflags}"x != x ] && %{_fix_broken_configure_for_lto}; \
  %{?_ld_as_needed:%{__fix_libtool_from_moving_options_after_libs} ;} \
  [ "%_configure_gnuconfig_hack" = 1 ] && for i in $(find $(dirname %{_configure}) -name config.guess -o -name config.sub) ; do \
      [ -f /usr/lib/rpm/%{_vendor}/$(basename $i) ] && %{__rm} -f $i && %{__cp} -fv /usr/lib/rpm/%{_vendor}/$(basename $i) $i ; \
  done ; \
  [ "%_configure_libtool_hardening_hack" = 1 ] && [ x != "x%{_hardened_ldflags}" ] && \
      for i in $(find . -name ltmain.sh) ; do \
        %{__sed} -i.backup -e 's~compiler_flags=$~compiler_flags="%{_hardened_ldflags}"~' $i \
      done ; \
  %{_configure} --build=%{_build} --host=%{_host} \\\
	--program-prefix=%{?_program_prefix} \\\
	--disable-dependency-tracking \\\
	%{?_configure_disable_silent_rules:--disable-silent-rules} \\\
	--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}

# ---- Build policy macros.

%__spec_install_pre %{___build_pre}\
    [ "$RPM_BUILD_ROOT" != "/" ] && rm -rf "${RPM_BUILD_ROOT}"\
    mkdir -p `dirname "$RPM_BUILD_ROOT"`\
    mkdir "$RPM_BUILD_ROOT"\
    %[0%{?_auto_set_build_cc} ? "%{set_build_cc}" : ""]\
    %[0%{?_auto_set_build_flags} ? "%{set_build_flags}" : ""]\
    export AM_UPDATE_INFO_DIR="no"\
%{nil}

# ---- Expanded at end of %install scriptlet.
%__arch_install_post   /usr/lib/rpm/check-buildroot

# Default extension to use (for man pages and info files)
%_extension .gz

# Build root policy macros. Standard naming:
# convert all '-' in basename to '_', add two leading underscores.
%__brp_chrpath /usr/lib/rpm/brp-chrpath %{buildroot}
%__brp_ldconfig /usr/lib/rpm/brp-ldconfig
%__brp_compress /usr/lib/rpm/brp-compress
%__brp_strip /usr/lib/rpm/brp-strip %{__strip}
%__brp_strip_lto /usr/lib/rpm/brp-strip-lto %{__strip}
%__brp_strip_comment_note /usr/lib/rpm/brp-strip-comment-note %{__strip} %{__objdump}
%__brp_strip_static_archive /usr/lib/rpm/brp-strip-static-archive %{__strip}
%__brp_check_elf_files /usr/lib/rpm/brp-check-elf-files
%__brp_python_bytecompile /usr/lib/rpm/brp-python-bytecompile "%{__python}" "%{?_python_bytecompile_errors_terminate_build}" "%{?_python_bytecompile_extra}"
%__brp_python_hardlink /usr/lib/rpm/brp-python-hardlink
# %__brp_remove_la_files /usr/lib/rpm/brp-remove-la-files
%__brp_remove_info_dir /usr/lib/rpm/brp-remove-info-dir
# %__brp_clean_perl_files /usr/lib/rpm/brp-clean-perl-files

%__os_install_post    \
    %{?__brp_ldconfig} \
    %{?__brp_compress} \
    %{!?__debug_package:\
    %{?__brp_strip} \
    %{?__brp_strip_comment_note} \
    } \
    %{?__brp_strip_lto} \
    %{?__brp_strip_static_archive} \
    %{?__brp_check_elf_files} \
    %{?__brp_remove_info_dir} \
    %{?py_auto_byte_compile:%{?__brp_python_bytecompile}} \
    %{?__brp_python_hardlink} \
%{nil}

%__spec_install_post\
    %{?__debug_package:%{__debug_install_post}}\
    %{?openEuler_delete_rpath:%{?__brp_chrpath}} \
    %{__arch_install_post}\
    %{__os_install_post}\
%{nil}

%install %{?_enable_debug_packages:%{?buildsubdir:%{debug_package}}}\
%%install\
%{nil}

#
# Should missing buildids terminate a build?
%_missing_build_ids_terminate_build    1

#
## Automatically compile python files
%py_auto_byte_compile 1

#
## Should python bytecompilation errors terminate a build?
%_python_bytecompile_errors_terminate_build 1
## Should python bytecompilation compile outisde python specific directories?
%_python_bytecompile_extra 1

# Use SHA-256 for FILEDIGESTS instead of default MD5
%_source_filedigest_algorithm 8
%_binary_filedigest_algorithm 8

# Use XZ compression for binary payloads
%_binary_payload w2.xzdio


# secure options for rpmbuild
#
# #hardened options
%_hardening_gcc_cflags	-specs=/usr/lib/rpm/generic-hardened-cc1
%_hardening_clang_cflags --config /usr/lib/rpm/generic-hardened-clang.cfg
%_hardening_cflags	 %{expand:%%{_hardening_%{toolchain}_cflags}}
%_hardening_ldflags	-Wl,-z,now %[ "%{toolchain}" == "gcc" ? "-specs=/usr/lib/rpm/generic-hardened-ld" : "" ]
# Use "%undefine _hardened_build" to disable.
%_hardened_build	1
%_hardened_cflags	%{?_hardened_build:%{_hardening_cflags}}
%_hardened_ldflags	%{?_hardened_build:%{_hardening_ldflags}}

#secure options pie
%_sec_opt_build  1
#Use "%undefine _sec_opt_build" to disable.
#Use "%undefine _pie_build" to disable.
%_pie_build     1
%_pie_pre_cflags   -specs=/usr/lib/rpm/generic-pie-cc1
%_pie_pre_ldflags  -Wl,-z,now -specs=/usr/lib/rpm/generic-pie-ld
%_pie_cflags       %{?_sec_opt_build:?_pie_build:%{_pie_pre_cflags}}
%_pie_ldflags      %{?_sec_opt_build:?_pie_build:%{_pie_pre_ldflags}}

#Use "%undefine _fs_build" to disable.
%_fs_build      1
%_fs_pre_cflags    -specs=/usr/lib/rpm/generic-fs-cc1
%_fs_cflags        %{?_fs_build:%{_fs_pre_cflags}}


# Fail linking if there are undefined symbols.  Required for proper
# ELF symbol versioning support.  Disabled by default.
# Use "%define _ld_strict_symbol_defs 1" to enable.
#%_ld_strict_symbol_defs		1
%_ld_symbols_flags		%{?_ld_strict_symbol_defs:-Wl,-z,defs}

# use "%define _ld_as_needed 1" to enable.
# %_ld_as_needed		1
%_ld_as_needed_flags	%{?_ld_as_needed:-Wl,--as-needed}

# LTO is the default in openEuler since 25.03.
#   "%define _lto_cflags %{nil}"  to opt out
#
# We currently have -ffat-lto-objects turned on out of an abundance of
# caution.  To remove it we need to do a check of the installed .o/.a files
# to verify they have real sections/symbols after LTO stripping.  That
# way we can detect installing an unusable .o/.a file.
%_gcc_lto_cflags	-flto=auto -ffat-lto-objects
%_clang_lto_cflags	-flto=thin
%_lto_cflags		%{expand:%%{_%{toolchain}_lto_cflags}}

%_general_options         -O2 %{?_lto_cflags} -g -grecord-gcc-switches -pipe -fstack-protector-strong %[ "%{toolchain}" == "clang" ? "-fgcc-compatible" : "" ]
%_warning_options         -Wall -Werror=format-security
%_preprocessor_defines    -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS

%__global_compiler_flags %{_general_options} %{_warning_options} %{_preprocessor_defines} %{_hardened_cflags}

# Automatically trim changelog entries after 2 years
%_changelog_trimtime	%{lua:print(os.time() - 2 * 365 * 86400)}

#==============================================================================
# ---- Generic auto req/prov filtering macros

# prevent anything matching from being scanned for provides
%filter_provides_in(P) %{expand: \
%global __filter_prov_cmd %{?__filter_prov_cmd} %{__grep} -v %{-P} '%*' | \
}

# prevent anything matching from being scanned for requires
%filter_requires_in(P) %{expand: \
%global __filter_req_cmd %{?__filter_req_cmd} %{__grep} -v %{-P} '%*' | \
}

# filter anything matching out of the provides stream
%filter_from_provides() %{expand: \
%global __filter_from_prov %{?__filter_from_prov} | %{__sed} -e '%*' \
}

# filter anything matching out of the requires stream
%filter_from_requires() %{expand: \
%global __filter_from_req %{?__filter_from_req} | %{__sed} -e '%*' \
}

# actually set up the filtering bits
%filter_setup %{expand: \
%global _use_internal_dependency_generator 0 \
%global __deploop() while read FILE; do echo "${FILE}" | /usr/lib/rpm/rpmdeps -%{1}; done | /bin/sort -u \
%global __find_provides /bin/sh -c "%{?__filter_prov_cmd} %{__deploop P} %{?__filter_from_prov}" \
%global __find_requires /bin/sh -c "%{?__filter_req_cmd}  %{__deploop R} %{?__filter_from_req}" \
}

# compare two versions, returns -1, 0, 1, ~~~
%rpm_vercmp() %{lua:print(rpm.expand('%1') == '~~~' and '~~~' or rpm.vercmp(rpm.expand('%1'), rpm.expand('%2')))}
# expand to the installed version of a package/provides
%pkg_version() %(LC_ALL=C rpm -q --whatprovides --qf "%%{version}" "%1" | sed -e "s/^no package provides .*/~~~/")
# compare the installed version to a value. returns -1, 0, 1, ~~~
%pkg_version_cmp() %{expand:%{expand:%%%%{rpm_vercmp %%{pkg_version %1} %%2}}}
# convenience/readability
%pkg_vcmp() (%{expand:%%{pkg_version_cmp %1 %3}} %2 0)

#arches macros
%generic_arches %{ix86} x86_64 %{arm} aarch64 loongarch64 powerpc64le ppc64le
%ldc_arches %{generic_arches}
%valgrind_arches %{generic_arches}
%nodejs_arches %{generic_arches} riscv64
%ldc_arches %{generic_arches}
%mono_arches %{generic_arches}
%fpc_arches %{generic_arches}
%ghc_arches_with_ghci %{generic_arches}
%ghc_arches  %{generic_arches}
%GNAT_arches %{GPRbuild_arches} %{generic_arches}
%GPRbuild_arches  %{generic_arches}
%nim_arches	 %{generic_arches}
%ocaml_native_compiler   %{generic_arches} riscv64
%ocaml_natdynlink        %{generic_arches} riscv64
%ocaml_native_profiling  %{generic_arches} riscv64
%openblas_arches 	 %{generic_arches} riscv64

#%ldconfig /sbin/ldconfig
%ldconfig_post(n:) %{?ldconfig:%post -p %ldconfig %{?*} %{-n:-n %{-n*}}\
%end}
%ldconfig_postun(n:) %{?ldconfig:%postun -p %ldconfig %{?*} %{-n:-n %{-n*}}\
%end}
%ldconfig_scriptlets(n:) %{?ldconfig:\
%ldconfig_post %{?*} %{-n:-n %{-n*}}\
%ldconfig_postun %{?*} %{-n:-n %{-n*}}\
}

# Some miscellaneous macros
%_metainfodir %{_datadir}/metainfo
%rpmmacrodir /usr/lib/rpm/macros.d

# arches that mono builds on
%_monogacdir %{_monodir}/gac
%_monodir %{_prefix}/lib/mono

# ---- VPATH default settings
%_vpath_builddir %_target_platform
%_vpath_srcdir .


# ---- custom macros
%disable_rpath \
sed -i 's|^hardcode_libdir_flag_spec=.*|hardcode_libdir_flag_spec=""|g' libtool \
sed -i 's|^runpath_var=LD_RUN_PATH|runpath_var=DIE_RPATH_DIE|g' libtool

%delete_la_and_a \
find "$RPM_BUILD_ROOT" -type l -name '*.la' 2>/dev/null -print0 | xargs -0 grep --fixed-strings '.la - a libtool library file' --files-with-matches --null | xargs -0 rm --force \
find "$RPM_BUILD_ROOT" -type f -name '*.la' 2>/dev/null -print0 | xargs -0 grep --fixed-strings '.la - a libtool library file' --files-with-matches --null | xargs -0 rm --force \
find "$RPM_BUILD_ROOT" -type l -name "*.a" -delete \
find "$RPM_BUILD_ROOT" -type f -name "*.a" -delete

%delete_la find $RPM_BUILD_ROOT -type f -name "*.la" -delete

%chrpath_delete find $RPM_BUILD_ROOT/ -type f -exec file {} ';' | grep "\\<ELF\\>" | awk -F ':' '{print $1}' | xargs -i chrpath --delete {}

%package_help        \
%package        help \
Summary:        Documents for %{name} \
Buildarch:      noarch \
\
%description help \
Man pages and other related documents for %{name}.

#%sbin_installinfo_rm bc.info
#%sbin_installinfo_rm bc.info.gz

%install_info() \
/sbin/install-info %1 %{_infodir}/dir || :

%install_info_rm() \
/sbin/install-info --remove %1 %{_infodir}/dir || :

# macros that used for perl
%__perl                 /usr/bin/perl
%requires_eq()  %(LC_ALL="C" echo '%*' | xargs -r rpm -q --qf 'Requires: %%{name} = %%{epoch}:%%{version}\\n' | sed -e 's/ (none):/ /' -e 's/ 0:/ /' | grep -v "is not")
%perl_sitearch  %(eval "`%{__perl} -V:installsitearch`"; echo $installsitearch)
%perl_sitelib   %(eval "`%{__perl} -V:installsitelib`"; echo $installsitelib)
%perl_vendorarch %(eval "`%{__perl} -V:installvendorarch`"; echo $installvendorarch)
%perl_vendorlib  %(eval "`%{__perl} -V:installvendorlib`"; echo $installvendorlib)
%perl_archlib   %(eval "`%{__perl} -V:installarchlib`"; echo $installarchlib)
%perl_privlib   %(eval "`%{__perl} -V:installprivlib`"; echo $installprivlib)
