#!/bin/sh

# usage: girar-nmu-local-build [options] <list of names> [ -- hsh <hasher arguments> ]

TASKID=
OUTGITS=OUT.gits
OUTSRPMS=OUT.SRPMS
SRPMOPTS=
GITOPTS=
ignore_failure=
commit=
while getopts cfG:hS:q opt; do
	case "$opt" in
		c) commit='--commit'
		   readonly commit ;;
		G) OUTGITS="${OPTARG:?}" 
			 ;;
		S) OUTSRPMS="${OPTARG:?}"
			 ;;
		f) ignore_failure=1
		   readonly ignore_failure ;;
		h) pod2usage --exit=0 "$0"; exit 0 ;;
		*) pod2usage --exit=2 "$0"; exit 2 ;;
	esac
done
shift "$((OPTIND-1))"

names=
hshargs=
endname=
for arg in "$@"; do
    if [ $arg = '--' ]; then
	endname=1
    elif [ -z "$endname" ]; then
	names="$names $arg"
    else
	hshargs="$hshargs $arg"
    fi
done
[ -z "$hshargs" ] && \
if [ -z "$ignore_failure" ]; then
    hshargs="hsh --with-stuff"
else
    hshargs="hsh"
fi

rebuild()
{
    local name="$1"
    if [ -d "$OUTGITS/$name.git" ]; then
	pushd "$OUTGITS/$name.git"
	echo gear --hasher -- $hshargs
	gear $commit --hasher -- $hshargs
	RETVAL=$?
	popd >/dev/null
	return $RETVAL
    elif [ -d "$OUTSRPMS/$name" ]; then
	if [ -e "$OUTSRPMS/$name/"*.src.rpm ]; then
	    echo $hshargs "$OUTSRPMS/$name/"*.src.rpm
	    $hshargs "$OUTSRPMS/$name/"*.src.rpm
	    return $?
	elif [ -e "$OUTSRPMS/$name/"*.tar ]; then
	    echo $hshargs "$OUTSRPMS/$name/"*.tar
	    $hshargs "$OUTSRPMS/$name/"*.tar
	    return $?
	else
	    echo "ERROR: strange: neither src.rpm nor tar is not found in $OUTSRPMS/$name/. maybe error during girar-nmu-prepare?."
	    exit 3;
	fi
    else
	echo "ERROR: NMU package not found for $name. run girar-nmu-prepare first."
	exit 3;
    fi
}

for name in $names; do
    if ! rebuild $name && [ -z "$ignore_failure" ] ; then
	echo "ERROR: build failed for $name"
	exit 4;
    fi
done

: <<'__EOF__'

=head1	NAME

girar-nmu-local-build - rebuild generated packages in prescribed order.

=head1	SYNOPSIS

B<girar-nmu-local-build>
[B<-h>] 
[B<-c>] 
[B<-f>] 
[B<-G> I<path/to/OUT.gits dir>]
[B<-S> I<path/to/OUT.SRPMS dir>]
I<name ...>
[B<--> hsh <hasher arguments...>]

=head1	DESCRIPTION

B<girar-nmu-local-build>
rebuild packages generated by B<girar-nmu-prepare> in prescribed order.
The utility invokes 

Example: 
girar-nmu-local-build `cat names` -- hsh --mountpoints=/proc /tmp/hasher

=head1	OPTIONS

=over

=item	B<-c>

Add --commit to gear options.

=item	B<-G> I<dir>

name of output directory with Git repositories.
Default is "OUT.gits".

=item	B<-S> I<dir>

name of output directory with src.rpms.
Default is "OUT.SRPMS".

=item	B<-f>

Continue building packages even if some builds fail.

=item	B<-h>

Display this help and exit.

=back

=head1	AUTHOR

Written by Igor Vlasenko <viy@altlinux.org>.

=head1	COPYING

Copyright (c) 2010 Igor Vlasenko, ALT Linux Team.

This 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 2 of the License, or (at your option) any later version.

=cut

__EOF__
