#!/bin/sh
##
#  Korinf project
#
#  Copying functions
#
#  Copyright (c) Etersoft <http://etersoft.ru> 2005-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/>.
##


# Cleanup target dir, used for all systems
prepare_copying()
{
	# Remove old packages from main dir
	if [ -n "$MAINFILESLIST" ] ; then
		mkdir -p $DESTDIR || sleep 100
		mkdir -p $DESTDIR || fatal "Can't create $DESTDIR"
		echo "Removing old '$MAINFILESLIST' from $DESTDIR..."
		pushd $DESTDIR >/dev/null || return 1
		rm -fv $EXPMAINFILES
		popd >/dev/null
	fi

	# Remove old packages from extra dir
	if [ -n "$EXTRAFILESLIST" ] ; then
		mkdir -p $DESTDIR/extra || sleep 100
		mkdir -p $DESTDIR/extra || fatal "Can't create $DESTDIR/extra"
		echo "Removing old '$EXTRAFILESLIST' from $DESTDIR/extra..."
		pushd $DESTDIR/extra >/dev/null || return 1
		rm -fv $EXPEXTRAFILES
		popd >/dev/null
	fi

}

gen_base_apt_rpm()
{
	if [ ! -d "$DESTDIR/RPMS.main" ] ; then
		ln -s ./ $DESTDIR/RPMS.main
	fi
	genbasedir --create --progress --topdir=$TARGETPATH $dist main
	#chmod o+r $DIR/* -R
	cat <<EOF > $DESTDIR/base/README.korinf.txt
You can add this repo to APT sources.list:
rpm file:$TARGETPATH $dist main
EOF
}


copying_packages()
{
	local RC=0
	local i
	prepare_copying

	pushd $BUILTRPM >/dev/null || warning "Can't cd to built rpm dir '$BUILTRPM'"
	echo "Copying $TARGET packages from $BUILTRPM"

	# Don't public debug packages now (it may contain source files)
	rm -f *${BUILDNAME}-debuginfo* *${BUILDNAME}-debug-*

	if [ -n "$MAINFILESLIST" ] ; then
		echo "Copying built packages to $DESTDIR..."
		cp -v $EXPMAINFILES $DESTDIR/ || { RC=1 ; warning "Cannot copy new packages $EXPMAINFILES" ; }
	fi

	if [ -n "$EXTRAFILESLIST" ] ; then
		echo "Copying built packages to $DESTDIR/extra..."
		cp -v $EXPEXTRAFILES $DESTDIR/extra/ || { RC=1 ; warning "Cannot copy extra packages $EXPEXTRAFILES" ; }
	fi

	# Return OK if one of files is exists
	for i in $EXPMAINFILES $EXPEXTRAFILES ; do
		test -r $i && RC=0
	done

	popd >/dev/null

	# remove fatal flag
	rm -fv $DESTDIR/log/$BUILDNAME.autobuild.failed

	# FIXME
	chmod ug+rw $DESTDIR/* -R 2>/dev/null
	chmod o+r $DESTDIR/* -R 2>/dev/null

	case $dist_name in
		"ALTLinux")
			gen_base_apt_rpm
			;;
		*)
			;;
	esac

	return $RC
}
