#!/bin/sh
# 2003-2005 (c) Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# BSH - build source; use hasher
# Public domain
# 06.02.05
# 15.04.05 add other repository support
# 05.09.05 major rewrite code
#  ()       hasher
#  ̣   (  -r)
#      ( -m)
# TODO:   
# TODO:    ??
# TODO:     1 ?
# FIXME:  -M24 2 
# TODO:  M  ,      ( myhsh)

. /etc/rpm/etersoft-build-functions

RESULT=0
REMCOM=
detect_target_env "$@"

#############################
name=${0##*/}
Descr="$name - BSH - build source; use hasher"
Usage="Usage: $name [-r -s -u -m] spec..."

phelp()
{
	echog "$Descr"
	echog "$Usage"
	echog "Options:"
	echog " -r - remote build"
}

while getopts :hru opt; do
    case $opt in
    h) phelp; exit 0;;
    r) REMOTEBUILD=1 ;;
    u) UPLOADNOW=1 ;;
    +?) 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
shift $((OPTIND - 1))

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

#############################


#echog "Packing without check of build dependencies for packages"
#NODEPS="--nodeps"
#LISTBUILT=""
build_list_and_args "$@"
#echo ${LISTRPMARGS/\-m/} @ ${LISTRPMARGS} @${LISTNAMES}
pack_src_rpm ${LISTRPMARGS/\-m/} --nodeps

add_changelog -e "- new version" $LISTNAMES && { echog "Please check Changelog entry" ; exit 1 ; }

if  [ -n "$REMOTEBUILD" ] ; then
	echog "Check access to SSH private key..."
	ssh-add -l || ssh-add
	test -n "$BUILDSERVER" || { echog "Please set BUILDSERVER in config file" ; exit 1; }
	test -n "$REMOTERPMDIR" || REMOTERPMDIR=`ssh $BUILDSERVER echo $HOME`/RPM
	echo
	echog "############ Build at build server '$BUILDSERVER' (with $LISTRPMARGS options) ############"
	echo
	echog "==== Copying to build server ====="
	echog "It is recommended to rename old version at server for save traffic during rsync"
	cd $RPMDIR/SRPMS && rsync -va --partial --progress --checksum \
	 	-e ssh $LISTBUILT $BUILDSERVER:$REMOTERPMDIR/SRPMS/ || exit 1
	ssh $BUILDSERVER "cd $REMOTERPMDIR/SRPMS && time myhsh $MENVARG $LISTRPMARGS $LISTBUILT"
	RESULT=$?
	echo "-------------------------------"
	echog "It was remote build"
else
	cd $RPMDIR/SRPMS && time myhsh $MENVARG $LISTRPMARGS $LISTBUILT
	RESULT=$?
	echo "-------------------------------"
fi

cd -

if [ "$RESULT" = "0" ] ; then
	test -n "$UPLOADNOW" && rpmbs -u $LISTNAMES
fi
exit $RESULT
