#!/bin/sh
##
#  Korinf project
#
#  Windows build related functions
#
#  Copyright (c) Etersoft <http://etersoft.ru> 2005, 2006, 2007, 2009, 2013
#  Copyright (c) Vitaly Lipatov <lav@etersoft.ru> 2009, 2014
#
#  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 rpm build

assert_var RPMDIR
assert_var BUILDNAME PACKAGEVERSION PACKAGERELEASE
assert_var BUILDSRPM

build_windows()
{
	# prevent gear detecting (operate inside our dir)
	export IGNOREGEAR=1

	# NOTE: we can do cd to some other dir...
	export RPMTOPDIR=$RPMDIR/BPW
	rm -rf $RPMTOPDIR/
	
	uni_rpminstall $BUILDSRPM

	# unpack sources and apply patches
	uni_rpmbuild $RPMTOPDIR/SPECS/*.spec -bp -v --nodeps || return

	# FIXME: hack about build dir
	cd $RPMTOPDIR/BUILD/$BUILDNAME-$PACKAGEVERSION/ || return

	# if all repo is packed
	local BUILDSCRIPT=.gear/mingwbuild.sh
	if [ ! -f $BUILDSCRIPT ] ; then
		# compatibility
		local BUILDSCRIPT=./etersoft/mingwbuild.sh
		if [ ! -f $BUILDSCRIPT ] ; then
			BUILDSCRIPT=./korinf/mingwbuild.sh
			if [ ! -f $BUILDSCRIPT ] ; then
				warning "It is needed to put $BUILDSCRIPT script in the tarball sources"
				return 1
			fi
		fi
	fi

	# Build to. Args: NAME VERSION RELEASE DESTDIR
	bash -x $BUILDSCRIPT $BUILDNAME $PACKAGEVERSION $PACKAGERELEASE $RPMTOPDIR/RPMS
	local RES=$?
	cd -

	# return error if have got error
	[ "$RES" = "0" ] || return $RES

	# Expand MAINFILELIST, EXTRAFILELIST
	prepare_filelist
}

copying_windows()
{
	echo "Copying to ftp"
	clean_copying_destination
	mkdir -p $DESTDIR
	cp -v $RPMTOPDIR/RPMS/*.exe $DESTDIR || { warning "Cannot copy packages" ; return 1; }
	echo "Done with copying"
	mark_build_done
}

clean_windows()
{
	uni_rpmrm *.spec
	echo "Cleaning $RPMTOPDIR/"
	rm -rf $RPMTOPDIR/
}
