#!/bin/sh
##
#  Korinf project
#
#  Common script for build any package in build farm
#
#  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 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 General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

# load common functions, compatible with local and installed script
. `dirname $0`/../share/eterbuild/korinf/common

if [ -z "$1" ] || [ "$1" = "-h" ]; then
	echo "Use: korinf [-r version ] [System/Version] package.spec|PackageName [TARGETDIR]" >&2
	echo "     with package.spec use target as rpmpub" >&2
	echo "     with packageName build in BuildFarm" >&2
	echo "     TARGETDIR - target dir instead default" >&2
	echo "     version - set target project version" >&2
	exit 1
fi

kormod korinf
load_mod spec rpm etersoft

# publish to unstable by default
ALPHA=
if [ "$1" = "-r" ] ; then
	ALPHA=$2
	ALPHAARG="$1 $2"
	shift 2
fi


# Using arg 1 as rebuild list
# if not "Package DIR"
if [ -n "$2" ] && [ ! -d "$2" ]; then
	# S/V Package DIR
	# S/V Package
	REBUILDLIST=$1
	shift
fi

BUILDNAME=$1
shift

if [ -n "$1" ] ; then
	ETERDESTSRPM=$1
	shift
fi

# TODO: for BuildFarm we had packagename by default
SUBDIR=

# if package name, not spec
if [ -n "${BUILDNAME/*.spec/}" ] ; then
	[ -n "$1" ] || ETERDESTSRPM=$BUILDFARMDIR
	# FIXME:
	# For build farm check global distro.list before build for all
	if [ "$REBUILDLIST" = "$KORINFETC/lists/all" ] ; then
		if [ -r "$ETERDESTSRPM/distro.list" ] ; then
			REBUILDLIST=$ETERDESTSRPM/distro.list
			echo "Build $BUILDNAME according to distro.list from $ETERDESTSRPM"
		fi
	fi
	build_project $ETERDESTSRPM "$BUILDNAME" "$SUBDIR" $@
	exit $?
else
	SPECNAME=$BUILDNAME
	if [ -z "$ETERDESTSRPM" ] ; then
		ETERDESTSRPM=$(get_etersoft_srpm_path $SPECNAME "$ALPHA")
		if [ ! -d "$ETERDESTSRPM" ] ; then
			ETERDESTSRPM=$BUILDFARMDIR
		fi
	fi
	BUILDNAME=$(eval_spec $SPECNAME | get_var "Name")
	rpmpub $ALPHAARG $SPECNAME $ETERDESTSRPM || exit 1
fi

# Build from spec (if default BuildFarm, get from spec)
if [ "$ETERDESTSRPM" = "$BUILDFARMDIR" ] ; then
	ETERDESTSRPM=$(get_etersoft_srpm_path $SPECNAME "$ALPHA")
fi

test -d "$ETERDESTSRPM" || fatal "You need run with exists dir to publish src.rpm project (I checked $ETERDESTSRPM, it is non exists)"

echo "Run with additional options: $@"
build_project $ETERDESTSRPM/.. "$BUILDNAME" "$SUBDIR" $@
