#!/bin/sh
# 2003-2010 (c) Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain
#
# BSH - build source; use hasher
#
# Создаёт пакет(ы) по указанным спекам и собирает в hasher

# load common functions, compatible with local and installed script
. `dirname $0`/../share/eterbuild/functions/common
load_mod rpm git buildsrpm

RESULT=0
REMCOM=
COMMIT=

#############################
Usage="Usage: $name [-r -s -u -m -i -c] [-f] [spec or src.rpm]..."
function mygetopts()
{
name=${0##*/}
Descr="$name (Build Source in the Hasher)  - build [from] source; use hasher"

phelp()
{
	echog "$Descr"
	echog "$Usage"
	echo
	echog "Options:"
	echog "   -u  sign and run gear build task after build"
	echog "   -i  install built packages in test hasher (via loginhsh -t)"
	echog "   -f  force tag set (see rpmbs --help)"
	echo
	echog "Ext. options:"
	echog "   -c  build without stuff (without previous built packages)"
	echog "   -s  sign (and move to dir ETERDESTSRPM if defined) after build"
	echog "   -t  make temporary commit before build (rpmbb like behavior)"
	echog "   -l  lazy cleanup (clean before build, not after)"
	echog "   -b REPONAME  binary repository name (4.1, p5, t6 and so on)"
}

while getopts :htb: opt; do
    case $opt in
    h) phelp; exit 0;;
    t) COMMIT="--commit" ;;
    b) BINARYREPONAME=$OPTARG ;;
    +?) 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-1)); break;
    esac
done

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

LISTRPMARGS=$@

}
#############################

set_girar_host $1 && shift

parse_cmd_pre_spec "$@"
mygetopts $LISTARGS
# see functions/alt:set_binaryrepo() for BINARYREPONAME
set_binaryrepo $MENV

[ -n "$LISTNAMES" ] || fatal "Run with exists specs as arg"

# Skip for prev. packed src.rpm
if estrlist has spec "$LISTNAMES" ; then
	# If fail, we already has correct changelog
	add_changelog_helper "- new version" $LISTNAMES
fi

# We do not not pass args for myhsh here...
# FIXME: не обрабатывает два пропускаемых вместе параметра
pack_src_rpm $COMMIT $(drop_args "$LISTRPMARGS" s u i c l f a A)

# TODO: use gear --hasher directly, drop myhsh

if rhas "$LISTNAMES" spec ; then
	set_specdir $LISTNAMES
fi

docmd time $ETERBUILDBIN/myhsh $MENVARG $(drop_args "$LISTRPMARGS" f u a A) $LISTBUILT
RESULT=$?
# remove generated src.rpm
for i in $LISTBUILT ; do
	estrlist has $i $LISTNAMES || rm -f $i
done

date
echo "-------------------------------"

# make src.rpm if build OK and we have options for rpmbs

RPMBSARGS=$(drop_args "$LISTRPMARGS" i c l)
if [ ! "$RESULT" = "0" ] || [ -z "$RPMBSARGS" ]; then
	exit $RESULT
fi

is_gear $SPECDIR && TSKLIST=$LISTNAMES || TSKLIST=$LISTBUILT

docmd $ETERBUILDBIN/rpmbs $GIRARHOST $MENVARG $RPMBSARGS $TSKLIST

