#!/bin/sh -x
##
#  Korinf project
#
#  After build install functions
#
#  Copyright (c) Etersoft <http://etersoft.ru> 2005-2010, 2012
#  Copyright (c) Vitaly Lipatov <lav@etersoft.ru> 2009-2012
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Affero General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.

#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Affero General Public License for more details.

#  You should have received a copy of the GNU Affero General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

load_mod tarball

# install built packages
install_built_packages()
{
	assert_var DISTRNAME INTBUILT EPMCMD
	
	#if [ $PKGVENDOR == "gentoo" ]
	#then
	#	run_in_chroot $dist "cd $INTBUILT && ls -a && ./${INSTALLBUILTSCRIPTNAME}"
		
	run_in_chroot $dist "cd $INTBUILT && ls -l && bash -x /usr/bin/epm --verbose --auto --force install ${EXPMAINFILES} ${EXPEXTRAFILES}" && return
	local status="$?"

	echo "epm install status: $status"
	# if status is skipped
	if [ "$status" = "22" ] ; then
		return 22
	fi

	# it is failed for all packages except eepm and rpm-build-altlinux-compat
	if [ -z "$INITIALBOOTSTRAP" ] ; then
		set_build_failed
		return
	fi

	# Bootstrap install eepm (get command from host's epm)
	local INSTALLCOMMAND
	INSTALLCOMMAND=$(DISTRNAME=$DISTRNAME $EPMCMD --auto --show-command-only install) || { warning "Can't get install command" ; return 1 ; }
	[ -n "$INSTALLCOMMAND" ] || { warning "Got empty install command" ; return 1 ; }
	# CHECKME: why we need yes here
	run_in_chroot $dist "cd $INTBUILT && yes | $INSTALLCOMMAND ${EXPMAINFILES} ${EXPEXTRAFILES}" #|| set_build_failed
	if [ "$BUILDNAME" = "eepm" ] ; then
		run_in_chroot $dist "epm -h >/dev/null" || set_build_failed
	fi
}

# Install required packages for build under the system (f.i., Debian/6.0)
# Assure we have needed build requirements
install_build_requires()
{
	local reqs dist="$1"
	load_mod repl rpm

	assert_var BUILDNAME TARGETARCH BUILDARCH TARGETSRPM PKGFORMAT
	assert_var BUILDERHOME
	assert_var dist

	# NOTE: possible side effect with redefined DISTRNAME, BUILDARCH, DISTRVERSION
	#parse_dist_name $dist

	# create needed files in home directory
	#init_home

	# Req build base system packages
	# Note: some additional requires we add in rpmbph
	# Note: sudo less for eepm
	# TODO: remove toolchain from this list
	# TODO: which for eepm
	local buildsystempkgs="which libtool automake autoconf rpm-build glibc-devel gzip bzip2 pkg-config cpio patch gcc coreutils grep make rpm gawk sudo less ed"

	# hack to prepare Debian based system
	[ "$PKGFORMAT" = "deb" ] && buildsystempkgs="$buildsystempkgs build-essential alien fakeroot debhelper"

	# TODO: convert reqs only here due alt macros?
	reqs="$($EPMCMD req "$TARGETSRPM" | grep -v "[<=>]" | xargs -n 1000 echo)"
	# super hack (reqs almost converted to target conventions (but only depends from BR)
	if echo "$reqs" | grep -q "python3-module-setuptools" ; then
		reqs="$(echo "$reqs" | sed -e 's|python3-module-setuptools||')"
		buildsystempkgs="$buildsystempkgs python3-module-setuptools"
	fi

	reqsbr="$(convert_pkgreqs_to_target $buildsystempkgs | xargs -n 1000 echo)"
	[ -z "$reqs$reqsbr" ] && return 0
	reqs="$(quote_pkgname $reqs)"
	reqsbr="$(quote_pkgname $reqsbr)"

	# run fixes only for rpm-build-altlinux-compat (as initial step)
	if  [ -n "$INITIALBOOTSTRAP" ] && [ "$BUILDNAME" = "rpm-build-altlinux-compat" ] ; then
		if [ "$PKGFORMAT" = "deb" ] && [ "$TARGETARCH" != "$BUILDARCH" ] ; then
			run_in_chroot $dist "dpkg --add-architecture i386" </dev/null
		fi

		if [ $DISTRNAME = "RockyLinux" ] ; then
			run_in_chroot $dist "epm --auto repo add epel ; epm --auto repo add powertools"
		fi

#		if [ "$DISTRNAME/$DISTRVERSION" = "AstraLinux/smolensk" ] ; then
#			# https://bugs.etersoft.ru/show_bug.cgi?id=15668#c12
#			run_in_chroot $dist "epm --auto install http://download.etersoft.ru/pub/download/astra-WE7xha2ia/ia32-libs_20220330+1.7se_amd64.deb"
#		fi

		if [ $DISTRNAME = "ROSA" ] ; then
			#run_in_chroot $dist "sed -i -e 's|executable-marked-as-config-file||' /usr/share/rpmlint/config.d/rosa.error.list"
			#cat <<EOF | run_in_chroot --user $dist "mkdir -p ~/.config/rpmlint/ && tee ~/.config/rpmlint"
			# https://www.apt-browse.org/browse/debian/jessie/main/all/rpmlint/1.6-2/file/etc/rpmlint/config
			# http://wiki.rosalab.ru/ru/index.php/Rpmlint
			cat <<EOF | run_in_chroot $dist "mkdir -p /etc/rpmlint/ && ! grep -q "subsys-not-used" /etc/rpmlint/config && tee -a /etc/rpmlint/config"
addFilter("E:.* subsys-not-used")
addFilter("E:.* postin-without-ldconfig")
addFilter("E:.* non-versioned-file-in-library-package")
addFilter("E:.* executable-marked-as-config-file")
addFilter("E:.* no-status-entry")
addFilter("E:.* no-chkconfig-line")
addFilter("E:.* init-script-name-with-dot")
addFilter("E:.* executable-in-library-package")
EOF
			# /tmp with noexec fails a test for %cross_compiling
			#run_in_chroot $dist "sed -i -e 's| /tmp/rpm| /var/tmp/rpm|g' /usr/lib/rpm/rosa/macros"
			# https://bugs.etersoft.ru/show_bug.cgi?id=15741#c3
			run_in_chroot $dist "cd /tmp ; which epm && { epm -q libpython3-devel.i686 || epm download libpython3-devel.i686 && epm install --force --nodeps libpython3*.rpm ;}"
		fi
	fi

	# prepare repository before install
	if [ -n "$BOOTSTRAP" ] ; then
		# safe input for eepm
		run_in_chroot $dist "which epm && epm --auto --verbose fix || true" </dev/null || { warning "epm fix failure" ; return 1 ; }
	fi

	# bootstrap install
#	if [ -n "$INITIALBOOTSTRAP" ] && [ "$BUILDNAME" = "eepm" ] ; then
	if [ -n "$INITIALBOOTSTRAP" ] ; then
		assert_var DISTRNAME
		local INSTALLCOMMAND
		#run_in_chroot "epm -h >/dev/null" || set_build_failed
		# Bootstrap install eepm (get command from host's epm)
		INSTALLCOMMAND=$(DISTRNAME=$DISTRNAME DISTRVERSION=$DISTRVERSION $EPMCMD --auto --show-command-only --nodeps install $reqsbr $reqs) || { warning "Can't get install command" ; return 1 ; }
		# CHECKME: why we need yes here
		run_in_chroot $dist "$INSTALLCOMMAND </dev/null" || return
	else
		# TODO: Appeared the backslashed quotes are required if package names contain parentheses
		# safe input for eepm
		run_in_chroot $dist "epm --auto update" </dev/null || return

		run_in_chroot $dist "epm --auto --verbose --skip-installed install $reqsbr" </dev/null
		RES=$?
		[ "$RES" != "0" ] && [ "$DISTRNAME" != "AstraLinuxSE" ] && return $RES # AstraLinuxSE due pcsxd failed

		run_in_chroot $dist "epm --auto --verbose --skip-installed install $reqs" </dev/null #|| return
		RES=$?
		[ "$RES" != "0" ] && [ "$DISTRNAME" != "AstraLinuxSE" ] && return $RES # AstraLinuxSE due pcsxd failed

		if [ "$TARGETARCH" != "$BUILDARCH" ] && [ "$PKGFORMAT" = "rpm" ] ; then
			case "$DISTRNAME" in
				RedOS|CentOS|RockyLinux|Fedora)
					# hack against architecture independent pkgconfig deps, see https://bugs.etersoft.ru/show_bug.cgi?id=14846#c9
					# FIXME: move hack with xargs -n1000 to epm
					# not all packages existed in i686
					#run_in_chroot $dist "epm --auto --verbose --skip-installed install $(epmqp devel .x86_64 | sed -e "s|\.x86_64|\.i686|" | xargs -n1000)" </dev/null || return
					run_in_chroot $dist "for i in \$(epmqp devel .x86_64 | sed -e 's|\.x86_64|\.i686|') ; do epm --auto --skip-installed install \$i ; done " </dev/null
					;;
			esac
		fi
	fi

	# run fixes only for rpm-build-altlinux-compat (as initial step)
	[ -n "$INITIALBOOTSTRAP" ] && [ "$BUILDNAME" = "rpm-build-altlinux-compat" ] || return 0

	# FIXME: Ubuntu 22.04 and Debian 11 only for now
	if [ "$PKGFORMAT" = "deb" ] ; then
		# https://bugs.etersoft.ru/show_bug.cgi?id=14664#c4
		run_in_chroot $dist 'echo "true" >/usr/bin/dh_strip_nondeterminism' </dev/null
	fi

	# fix libdir macros on deb platforms
	libdir32="%{_prefix}/lib/i386-linux-gnu"
	libdir64="%{_prefix}/lib/x86_64-linux-gnu"
	if [ "$DISTRNAME" = "AstraLinuxCE" ] || [ "$DISTRNAME" = "AstraLinuxSE" ] ; then
		libdir32="%{_prefix}/lib32/i386-linux-gnu"
	fi
	
	if [ "$TARGETARCH" != "$BUILDARCH" ] ; then
cat <<EOF | run_in_chroot $dist "mkdir -p /etc/rpm/$TARGETARCH-linux && tee /etc/rpm/$TARGETARCH-linux/macros"
# created with Korinf
# Inverted meaning!!!

# The system where built programs and libraries will run.
%_host            i686-redhat-linux-gnu
%_host_alias      i686-redhat-linux-gnu%{nil}
%_host_cpu        i686

# TODO: use standalone macros?
%_build            i686-redhat-linux-gnu
%_build_alias      i686-redhat-linux-gnu%{nil}
%_build_cpu        i686

# The system on which the package is built
#_build           x86_64-redhat-linux-gnu
#_build_alias     x86_64-redhat-linux-gnu%{nil}
#_build_cpu       x86_64
EOF
	fi

# biarch build (32 bit on 64 bit system)
	if [ "$PKGFORMAT" = "deb" ] && [ "$TARGETARCH" != "$BUILDARCH" ] ; then
cat <<EOF | run_in_chroot $dist "sed -i -e 's|^optflags: i586|optflags: i586 -O2 -g -m32 -march=i586|' /usr/lib/rpm/rpmrc ; mkdir -p /etc/rpm/$TARGETARCH-linux && tee /etc/rpm/$TARGETARCH-linux/macros"
# created with Korinf $(date)
# FIXME: by some reason really overrides in /usr/lib/rpm/rpmrc
%optflags               -O2 -g -m32 -g -march=i586

%__isa_name             x86
%__isa_bits             32
%__isa                  %{__isa_name}-%{__isa_bits}

# The default transaction color. This value is a set of bits to
# determine file and dependency affinity for this arch.
#       0       uncolored (i.e. use only arch as install hint)
#       1       Elf32 permitted
#       2       Elf64 permitted
%_transaction_color     0

#==============================================================================
# ---- configure macros.
#
%_libexecdir            %{_prefix}/lib
%_lib                   lib
%_libdir                $libdir32
EOF
	fi

# native 32 bit target
	if [ "$PKGFORMAT" = "deb" ] && [ "$BUILDARCH" = "i586" ] ; then
cat <<EOF | run_in_chroot $dist "mkdir -p /etc/rpm/$TARGETARCH-linux && tee /etc/rpm/$TARGETARCH-linux/macros"
# created with Korinf $(date)

%_libexecdir            %{_prefix}/lib
%_lib                   lib
%_libdir                $libdir32
EOF
	fi

# native 64 bit target
	if [ "$PKGFORMAT" = "deb" ] && [ "$TARGETARCH" = "x86_64" ] ; then
cat <<EOF | run_in_chroot $dist "mkdir -p /etc/rpm/$TARGETARCH-linux && tee /etc/rpm/$TARGETARCH-linux/macros"
# created with Korinf $(date)

%_libexecdir            %{_prefix}/lib
%_lib                   lib
%_libdir                $libdir64
EOF
	fi

}
