#!/bin/sh
# 2003-2005 (c) Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# BB - binary build (like rpm option -bb)
# Public domain
# 06.02.05
#   rpm-   
# :
# -  -
# TODO -M?
# TODO: -c

. /etc/rpm/etersoft-build-functions

# Start as helper
if [ "$1" = "--helper" ]; then
	shift
	cd $RPMDIR/SPECS && rpmbb "$@"
	exit $?
fi


#############################
name=${0##*/}
Descr="$name - build  binary rpm from spec"
Usage="Usage: $name [-c -p -i] spec..."

phelp()
{
	echog "$Descr"
	echog "$Usage"
	echog "Options:"
	echog " -c - compile"
	echog " -i - install and package"
	echog " -p - package installed"
}

while getopts :hcip opt; do
    case $opt in
    h) phelp; exit 0;;
    c) BUILDOPT="c" ;;
	i) BUILDOPT="i b" ;;
    p) BUILDOPT="b" ;;
    +?) echog "$name: options should not be preceded by a '+'." 1>&2; exit 2;;
#    ?)  echog "$name: $OPTARG: bad option.  Use -h for help." 1>&2 ; exit 2;;
	?) OPTIND=$((OPTIND-0)); break;
    esac
done

# remove args that were options
if [ $# -gt 1 ]; then 
	shift $((OPTIND - 1))
fi

if [ $# -lt 1 ]; then
    echog "$Usage"
	echog "Use -h for help."
    exit
fi

mkdir -p $LOGDIR
build_list_and_args "$@"
#echo $LISTRPMARGS @ $LISTARGS

if [ -n "$BUILDOPT" ] ; then
	for i in $BUILDOPT
	do
		rpmbuild -b$i $LISTNAMES $LISTRPMARGS --target $DEFAULTARCH --short-circuit
	done
	exit
fi


for i in $LISTNAMES
do
	build_rpms_name "$i"
	LOGFILE="$LOGDIR/`basename $NAMESRPMIN .src.rpm`$MENVARG.log"
	rm -f $LOGFILE.failed
	(rpmbuild -bb $LISTRPMARGS --target $DEFAULTARCH "$i" 2>&1 || touch $LOGFILE.failed) | tee $LOGFILE
	check_log $LOGFILE ; RES=$?
	if [ -f $LOGFILE.failed -o ! $RES = 0 ]
	then
		echo "!!!!!!!! ERROR !!!!!"
		echog "Failed with \$i"
		exit 1
	fi
done
echog "Built is done correctly"
exit 0


######################################################
# rpmbbr ========= 
RESULT=0
ssh-add -l || ssh-add

echog "Packing without check of build dependencies for packages"

NODEPS="--nodeps"
LISTBUILT=""
pack_src_rpm $LISTRPMARGS

echog "==== Copying to build server ====="
echog "It is recommended to rename old version at server for save traffic during rsync"
rsync -va --partial --progress --stats --checksum \
 	-e ssh $LISTBUILT $BUILDSERVER:/$RPMDIR/SRPMS/

echo
echog "############ Build at build server ############"
echo
ssh $BUILDSERVER rpm -ivh $LISTBUILT
ssh $BUILDSERVER rpmbb --helper "$@"
echo "-------------------------------"
echog "Remote build is done"

