###########################################################################
# Copyright (C) 2015-2021 IoT.bzh Company
#
# Author: Clément Bénier <clement.benier@iot.bzh>
# Author: Romain Forlot <romain.forlot@iot.bzh>
#
# $RP_BEGIN_LICENSE$
# Commercial License Usage
#  Licensees holding valid commercial IoT.bzh licenses may use this file in
#  accordance with the commercial license agreement provided with the
#  Software or, alternatively, in accordance with the terms contained in
#  a written agreement between you and The IoT.bzh Company. For licensing terms
#  and conditions see https://www.iot.bzh/terms-conditions. For further
#  information use the contact form at https://www.iot.bzh/contact.
#
# GNU General Public License Usage
#  Alternatively, this file may be used under the terms of the GNU General
#  Public license version 3. This license is as published by the Free Software
#  Foundation and appearing in the file LICENSE.GPLv3 included in the packaging
#  of this file. Please review the following information to ensure the GNU
#  General Public License requirements will be met
#  https://www.gnu.org/licenses/gpl-3.0.html.
# $RP_END_LICENSE$
###########################################################################

#---------- cross profile options Start ---------
# IoTBzh RPM macros to differentiate BuildRequires
# in a cross-compilation environment.
# Others macros useful to crosscompile
%_crosstarget			@TARGET@
%_crossroot			@CROSS_ROOT@

# RPM default value override to be sure to use a cross-
# compilation environment using autotool configure script
%_host				@HOST@
%_build			@BUILD@
%_target			@TARGET@
%_target_cpu			@CROSS_ARCH@

%_arch                  @CROSS_ARCH@
%_build_arch            @CROSS_ARCH@
%_gnu                   @GNU@
%_target_platform       %{_target_cpu}-%{_vendor}-%{_target_os}%{?_gnu}
%optflagscross          %{__global_compiler_flags} -fasynchronous-unwind-tables -fstack-clash-protection
%__isa_name             @CROSS_ARCH_ISA@
%__isa_bits             @CROSS_BITS@
%__isa                  %{__isa_name}-%{__isa_bits}
%_isa                   %{?__isa:(%{__isa})}%{!?__isa:%{nil}}

# WORKAROUND for specific macros that ask if we are on a fedora or rhel host.
# Needed to correctly expand some macros
# UPDATE: comment the fedora macros because it leads builders
# to download unknown dependencies when building for non-fedora distros
#%fedora 33

# Generic workaround to don't detect cross-compile environment when using autotool
# because using QEMU we are able to run binary of the target arch.
%_fix_configure \
        for f in $(find %{_builddir} -type f -name configure); do \
		grep -E 'BUILD_CFLAGS.*=.*\\${?CFLAGS}?' $f ||\
                sed -i 's:cross_compiling=yes:cross_compiling=no:' $f \
        done

# Override the default RedHat Compiler flags. This removes
# the annotated_build flags and the SSP flag.
%__global_compiler_flags	-O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -grecord-gcc-switches %{_hardened_cflags} --sysroot=%{_crossroot}

# Override the default compilation toolchain with the crosstool
%__ar				@CROSS_AR@
%__as				@CROSS_AS@
%__cc				@CROSS_CC@
%__cpp				@CROSS_CPP@
%__cxx				@CROSS_CXX@
%__ld				@CROSS_LD@
%__nm				@CROSS_NM@
%__objcopy			@CROSS_OBJCOPY@
%__objdump			@CROSS_OBJDUMP@
%__ranlib			@CROSS_RANLIB@
%__strip			@CROSS_STRIP@

# Override the default rpm macros that invokes build
# tools to add the crosscompile options at the end
%cmake \
  CFLAGS="${CFLAGS:-%optflags}" ; export CFLAGS ; \
  CXXFLAGS="${CXXFLAGS:-%optflags}" ; export CXXFLAGS ; \
  FFLAGS="${FFLAGS:-%optflags%{?_fmoddir: -I%_fmoddir}}" ; export FFLAGS ; \
  FCFLAGS="${FCFLAGS:-%optflags%{?_fmoddir: -I%_fmoddir}}" ; export FCFLAGS ; \
  %{?__global_ldflags:LDFLAGS="${LDFLAGS:-%__global_ldflags}" ; export LDFLAGS ;} \
  %__cmake \\\
		%{!?__cmake_in_source_build:-S "%{_vpath_srcdir}"} \\\
		%{!?__cmake_in_source_build:-B "%{__cmake_builddir}"} \\\
        -DCMAKE_C_FLAGS_RELEASE:STRING="-DNDEBUG" \\\
        -DCMAKE_CXX_FLAGS_RELEASE:STRING="-DNDEBUG" \\\
        -DCMAKE_Fortran_FLAGS_RELEASE:STRING="-DNDEBUG" \\\
        -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON \\\
        -DCMAKE_INSTALL_PREFIX:PATH=%{_prefix} \\\
        -DCMAKE_INSTALL_LIBDIR:PATH=%{_lib} \\\
        -DINCLUDE_INSTALL_DIR:PATH=%{_includedir} \\\
        -DLIB_INSTALL_DIR:PATH=%{_libdir} \\\
        -DSYSCONF_INSTALL_DIR:PATH=%{_sysconfdir} \\\
        -DSHARE_INSTALL_PREFIX:PATH=%{_datadir} \\\
        -DPYTHON_EXECUTABLE:FILEPATH=%{__python3} \\\
%%if "%{?_lib}" == "lib64" \
        %{?_cmake_lib_suffix64} \\\
%%endif \
        -DBUILD_SHARED_LIBS:BOOL=ON \\\
	    -DCMAKE_SYSTEM_PROCESSOR=$CROSS_ARCH \\\
        -DCMAKE_TOOLCHAIN_FILE=%{_datadir}/cmake/toolchain.cmake

%meson \
    %set_build_flags \
    %{shrink:%{__meson} setup \
        --cross-file=@CROSS_TARGET_CPU@-linux-gnu \
        --buildtype=plain \
        --prefix=%{_prefix} \
        --libdir=%{_libdir} \
        --libexecdir=%{_libexecdir} \
        --bindir=%{_bindir} \
        --sbindir=%{_sbindir} \
        --includedir=%{_includedir} \
        --datadir=%{_datadir} \
        --mandir=%{_mandir} \
        --infodir=%{_infodir} \
        --localedir=%{_datadir}/locale \
        --sysconfdir=%{_sysconfdir} \
        --localstatedir=%{_localstatedir} \
        --sharedstatedir=%{_sharedstatedir} \
        --wrap-mode=%{__meson_wrap_mode} \
        --auto-features=%{__meson_auto_features} \
        %{_vpath_srcdir} %{_vpath_builddir} \
        %{nil}}


%configure \
  %{set_build_flags}; \
  %{_fix_configure} \
  [ "%_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} \\\
        --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} \\\
        --with-systemdsystemunitdir=%{_unitdir} \\\
        --with-systemduserunitdir=%{_userunitdir} \\\
        --infodir=%{_infodir} \\\
        --with-sysroot=%{_crossroot} \\\
        --host=%{_host} \\\
        --build=%{_build}

# qmake flags for Qt4
%_qt4_qmake_flags \\\
        QMAKE_CC="%{__cc}" \\\
        QMAKE_CXX="%{__cxx}" \\\
        QMAKE_LINK="%{__cxx}" \\\
        QMAKE_CFLAGS="%{build_cflags}" \\\
        QMAKE_CXXFLAGS="%{build_cxxflags}" \\\
        QMAKE_LFLAGS="%{build_ldflags}" \\\
        QMAKE_INCDIR_QT="%{?_crossroot}%{_includedir}" \\\
        QMAKE_LIBDIR_QT="%{?_crossroot}%{_libdir}" \\\
        QMAKE_CFLAGS_DEBUG="${CFLAGS:-%{_qt4_optflags}}" \\\
        QMAKE_CFLAGS_RELEASE="${CFLAGS:-%{_qt4_optflags}}" \\\
        QMAKE_CXXFLAGS_DEBUG="${CXXFLAGS:-%{_qt4_optflags}}" \\\
        QMAKE_CXXFLAGS_RELEASE="${CXXFLAGS:-%{_qt4_optflags}}" \\\
        QMAKE_LFLAGS_DEBUG="${LDFLAGS:-%{_qt4_ldflags}}" \\\
        QMAKE_LFLAGS_RELEASE="${LDFLAGS:-%{_qt4_ldflags}}" \\\
        QMAKE_STRIP=

# qmake flags for Qt5
%_qt5_qmake_flags \\\
	QMAKE_CC="%{__cc}" \\\
        QMAKE_CXX="%{__cxx}" \\\
        QMAKE_LINK="%{__cxx}" \\\
        QMAKE_CFLAGS="%{build_cflags}" \\\
        QMAKE_CXXFLAGS="%{build_cxxflags}" \\\
        QMAKE_LFLAGS="%{build_ldflags}" \\\
        QMAKE_INCDIR_QT="%{?_crossroot}%{_includedir}" \\\
        QMAKE_LIBDIR_QT="%{?_crossroot}%{_libdir}" \\\
  	QMAKE_CFLAGS_DEBUG="${CFLAGS:-%{_qt5_optflags} %{?_qt5_cflags}}" \\\
  	QMAKE_CFLAGS_RELEASE="${CFLAGS:-%{_qt5_optflags} %{?_qt5_cflags}}" \\\
	QMAKE_CXXFLAGS_DEBUG="${CXXFLAGS:-%{_qt5_optflags} %{?_qt5_cxxflags}}" \\\
	QMAKE_CXXFLAGS_RELEASE="${CXXFLAGS:-%{_qt5_optflags} %{?_qt5_cxxflags}}" \\\
  	QMAKE_LFLAGS_DEBUG="${LDFLAGS:-%{_qt5_ldflags}}" \\\
  	QMAKE_LFLAGS_RELEASE="${LDFLAGS:-%{_qt5_ldflags}}" \\\
  	QMAKE_STRIP=

%cabal_db_path /builddir/ghc.pkg.conf.d

%cabal_update_package_db\
%{__rm} -rf %cabal_db_path\
%{_crosstarget}-ghc-pkg init %cabal_db_path\
for file in $(ls -1 %{_crossroot}%{ghclibdir}/package.conf.d/*conf)\
do\
    sed -r 's!(import-dirs: |library-dirs: |dynamic-library-dirs: |data-dirs: )!\\1'${CROSS_ROOT}'!' $file > %{cabal_db_path}/$(basename $file)\
done\
%{_crosstarget}-ghc-pkg --package-db=%{cabal_db_path} recache

%cabal_configure\
export LDFLAGS=$(echo $LDFLAGS | sed 's:-specs.*$::')\
%cabal_update_package_db\
%ghc_set_gcc_flags\
if ! [ -f Setup.hs -o -f Setup.lhs ]; then\
cp %{_datadir}/ghc-rpm-macros/Setup.hs .\
fi\
%cabal --version\
%cabal configure --prefix=%{_prefix} --with-compiler=%{_bindir}/%{_crosstarget}-ghc --with-strip=%{_crosstarget}-strip --package-db=%{cabal_db_path} --libdir=%{_libdir} --docdir=%{_ghcdocdir} --libsubdir='$compiler/$pkgid' --datasubdir='$pkgid' --libexecsubdir='$pkgid' --ghc %{?_ghcdynlibdir:--dynlibdir=%{_ghcdynlibdir}} %{!?ghc_without_dynamic    :--enable-executable-dynamic} %{?with_tests:--enable-tests} %{?ghc_subpackaging:--user}%{!?ghc_subpackaging:--global} --ghc-options="${CFLAGS:+$(echo ' '$CFLAGS | sed -e 's/ / -optc/g')} ${LDFLAGS:+$(echo ' '$LDFLAGS | sed -e 's/ / -optl/g')}" %{?cabal_configure_options} $cabal_configure_extra_options

# Generate the documentation doesn't need to use the cross-ghc which could
# fails with:
# haddock: panic! (the 'impossible' happened)
#  (GHC version 8.2.2 for x86_64-unknown-linux):
#	nativeCodeGen: No NCG for ARM64
%ghc_lib_build()\
%ghc_lib_build_without_haddock %{?1} %{?2}\
%if %{undefined without_haddock}\
%define pkgname %{?1}%{!?1:%{pkg_name}}\
%define pkgver %{?2}%{!?2:%{version}}\
if [ -n dist/build/libHS%{pkgname}-%{pkgver}*.so ]; then\
%cabal haddock --with-ghc=ghc --haddock-options=--optghc='-package-db=/usr/lib64/ghc-8.2.2/package.conf.d' --html --hyperlink-source --hoogle %{?cabal_haddock_options}\
fi\
%endif\
%{nil}

# Rely on the cross perl binary to get value
%__perl %{_crossroot}%{_bindir}/perl
# Perl macro : for the moment, LDDLFLAGS is handmade
#%__perl() /usr/bin/perl %{?*}\\\
#    PREFIX="%{_prefix}"\\\
#    CC="%{__cc}"\\\
#    CCFLAGS="%{build_cflags}"\\\
#    LDFLAGS="%{build_ldflags}"\\\
#    LD="%{__cc}"\\\
#    LDDLFLAGS="-lpthread -shared %{build_ldflags}"\\\
#    VENDORARCHEXP="%{?_crossroot}%{perl_vendorarch}"\\\
#    VENDORLIBEXP="%{?_crossroot}%{perl_vendorlib}"\\\
#    SITELIBEXP="%{?_crossroot}%{perl_sitelib}"\\\
#    SITEARCHEXP="%{?_crossroot}%{perl_sitearch}"\\\
#    PERL_ARCHLIB="%{?_crossroot}%{perl_archlib}"

#----------  cross profile options End ---------

# PYTHON
%__python3 %(if test -x %{_crossroot}/usr/libexec/platform-python; then echo %{_crossroot}/usr/libexec/platform-python;else echo /usr/libexec/platform-python;fi)
%python3_sitelib %(%{__python3} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib().replace('%{_crossroot}', ''))")
%python3_sitearch %(%{__python3} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib(1).replace('%{_crossroot}', ''))")
%python3_version %(%{__python3} -c "import sys; sys.stdout.write(sys.version[:3])")
%python3_version_nodots %(%{__python3} -c "import sys; sys.stdout.write(sys.version[:3].replace('.',''))")
%python3_platform %(%{__python3} -c "import sysconfig; print(sysconfig.get_platform())")
%python3_platform_triplet %(%{__python3} -c "import sysconfig; print(sysconfig.get_config_var('MULTIARCH'))")
%python3_ext_suffix %(%{__python3} -c "import sysconfig; print(sysconfig.get_config_var('EXT_SUFFIX'))")

# Use the slashes after expand so that the command starts on the same line as
# the macro
%py3_build() %{expand:\\\
  CFLAGS="${CFLAGS:-${RPM_OPT_FLAGS}}" LDFLAGS="${LDFLAGS:-${RPM_LD_FLAGS}}"\\\
  PYTHONHOME="%{?_crossroot}%{_usr}" \\\
  %{__python3} %{py_setup} %{?py_setup_args} build --executable="/usr/libexec/platform-python %{py3_shbang_opts}" %{?*}
  sleep 1
}

%__spec_autodep_pre %define __python3 /usr/libexec/platform-python

# Force using the buildroot python to correctly mangling the shebangs
%__brp_mangle_shebangs PYTHON3="/usr/libexec/platform-python" /usr/lib/rpm/@VENDOR@/cross-brp-mangle-shebangs %{?__brp_mangle_shebangs_exclude:--shebangs "%{?__brp_mangle_shebangs_exclude}"} %{?__brp_mangle_shebangs_exclude_file:--shebangs-from "%{__brp_mangle_shebangs_exclude_file}"} %{?__brp_mangle_shebangs_exclude_from:--files "%{?__brp_mangle_shebangs_exclude_from}"} %{?__brp_mangle_shebangs_exclude_from_file:--files-from "%{__brp_mangle_shebangs_exclude_from_file}"}


# undefine annobin
%_annobin_cflags %{nil}
%_annobin_gcc_plugin %{nil}

# override cmake.req for cross (replacing cmake-filesystem(_isa) with cross arch
%__cmake_requires       %{_rpmconfigdir}/cmake.req.cross
