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

convert_archlinux()
{
	assert_var TARGETBUILDNAME PACKAGEVERSION PACKAGERELEASE PKGVENDOR BUILDARCH PKGFORMAT

	# TODO: can be noarch (check the result package)
	prepare_convert

	local PKGARCH=${BUILDARCH/i586/i686}
	local TARGETPKG=$TARGETBUILDNAME-$PACKAGEVERSION-$PACKAGERELEASE$PKGVENDOR-$PKGARCH.$PKGFORMAT

	# FIXME: check get_target_deplist
	# make list in form 'item1', 'item2'
	# TODO: move to estrlist
	local prepreqs
	for i in $PKGREQLIST ; do
		# FIXME: handle first arg separately before the cycle
		#[ -z "$prepreqs" ] || prepreqs="$prepreqs, "
		prepreqs="$prepreqs'$i' "
	done
	prepreqs=$(estrlist uniq $prepreqs)

	cat <<EOF | run_in_chroot --user "bash -x -" || return
	umask 002
	mkdir -p ~/RPM/log

	rm -rf $WRKDIR/
	mkdir -p $WRKDIR/src/ && cd $WRKDIR/src/ || exit

	for i in $BUILTBINPKGLIST ; do
		pkg=$INTBUILT/\$(basename \$i)
		test -r \$pkg || exit
		# needs cpio package
		rpm2cpio \$pkg | cpio -dimv || exit
		# from rpmextract package
		#rpmextract.sh \$pkg || exit
		rm -f \$pkg
	done

	cd $WRKDIR/

	cat <<PKGEOF >PKGBUILD
# ArchLinux PKGBUILD generated by Korinf from $TARGETSRPM
# See http://wiki.etersoft.ru/Korinf for details

pkgname=$TARGETBUILDNAME
pkgver=$PACKAGEVERSION
# ERROR: pkgrel must be a decimal.
#pkgrel=$PACKAGERELEASE$PKGVENDOR
#Anton's correction (cut addition)
pkgrel=$(echo $(get_numpartrelease ${PACKAGERELEASE})| cut -f1 -d'.')
pkgdesc="$PKGCOMMENT"
depends=($prepreqs)
url=($PKGURL)
arch=(${PKGARCH})
license=('$PKGLICENSE')
packager="$PKGPACKAGER"

package() {
  #cd "\$srcdir/\$pkgname-\$pkgver"
  # we use just src
  cd "\\\$srcdir/"
  chmod -R go-w *
  cp -a * \\\$pkgdir
}
PKGEOF
	cat PKGBUILD

	# makepkg checks depends by default
	makepkg --nodeps || exit

	mv -v *.$PKGFORMAT $INTBUILT/
	rm -rf $WRKDIR/
	#rm -v $BUILTBINPKGLIST
	true
EOF

	# Skip, we can get packages locally
	#echo "$BUILTRPM/$TARGETPKG"
	#run_in_chroot --user "cat $INTBUILT/$TARGETPKG" >$BUILTRPM/$TARGETPKG || return
}

