#!/bin/sh
##
#  Korinf project
#
#  convert built packages in chrooted Linux system
#
#  Copyright (c) Etersoft <http://etersoft.ru> 2005, 2006, 2007, 2009
#  Copyright (c) Vitaly Lipatov <lav@etersoft.ru> 2009
#
#  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/>.
##

# We believe BUILDERHOME is clean already here

load_mod repl
kormod converts/common

# converts ALT src.rpm to target src.rpm and send it to build system
# used BUILDERHOME to put in src.rpm
convert_rpm_to_target()
{
	local dist=$1

	# FIXME: hack
	[ -n "$BUILDERHOME" ] || BUILDERHOME=/tmp/korinfer-$USER
	mkdir -p $BUILDERHOME

	# rpmbph will use DISTRNAME/DISTRVERSION and so on

	# FIXME: when build to remote dist, we need generic src.rpm
	echo "Convert '$BUILDSRPM' for $dist distro"
	rm -f $BUILDERHOME/tmp/$BUILDNAME*
	if [ -n "$MAKESPKG" ] ; then
		$RPMBP -v -z $BUILDSRPM
		BUILTRPM=~/$RPMSDIR
		return 0
	else
		ETERDESTSRPM=$BUILDERHOME/tmp $RPMBP -v -z $BUILDSRPM
		BUILTRPM=$BUILDERHOME/$RPMSDIR
	fi

	# Get real src.rpm name
	TARGETSRPM=$(echo $BUILDERHOME/tmp/$BUILDNAME*.src.rpm | head -n1)
	[ -r "$TARGETSRPM" ] && [ -f "$TARGETSRPM" ] || { warning "Can't read target $TARGETSRPM src.rpm" ; return 1 ; }

	if is_remote_build ; then
		cat $TARGETSRPM | run_in_chroot --user "mkdir -p /home/$INTUSER/tmp ; cat >/home/$INTUSER/tmp/$(basename $TARGETSRPM)"
		return
	else
		$SUDO chown $LOCUSER $TARGETSRPM
	fi

	return 0
}

# Note: all converts/ functions run in the package with rpm packages
# converts built rpm packages to target format
convert_rpm()
{
	assert_var BUILTRPM PKGFORMAT PKGVENDOR
	local RES=0

	pushd $BUILTRPM
	echo "Make target packages for $PKGFORMAT ($PKGVENDOR) from follow list:"
	ls -l

	case $PKGVENDOR in
		"gentoo")
			kormod converts/gentoo
#			convert_gentoo || fatal "Cannot convert for Gentoo"
			convert_gentoo
			RES=$?
			;;
		"archlinux")
			kormod converts/archlinux
			convert_archlinux
			RES=$?
			;;
		"freebsd")
			kormod converts/freebsd
			convert_freebsd
			RES=$?
			;;
		*)
			case $PKGFORMAT in
			    "deb")
				kormod converts/deb
				convert_debian
				RES=$?
				;;
			    "tgz")
				kormod converts/alien
				convert_by_target
				RES=$?
				;;
			    *)
				fatal "unknown $PKGFORMAT"
			esac
	esac

	popd
	return $RES
}

