#!/bin/sh

export LANG=C
export LANGUAGE=C

PROG=`basename $0`

show_help()
{
#  -q, --quiet                       try to be more quiet;
#  -v, --verbose                     print a message for each action;
	cat <<EOF
$PROG - script to build and test the set of packages in parallel. Current path must be valid autorepo directory.
Usage: $PROG [options]

Options:
  -j <N>,--jobs <N> number of hashers used; --number 1 .. --number <N>
  -d,--drop   drop package at first unsuccessful build
  -h, --help  show this text and exit.

Report bugs to http://bugzilla.altlinux.org/
EOF
	exit
}

rapid_drop_mode=
. autorepo-config
hasher_jobs=$AUTOREPO_DEFAULT_PARLLEL_BUILD

TEMP=`getopt -n $PROG -o dj:h -l jobs:,drop,help -- "$@"` ||
	show_help
eval set -- "$TEMP"

while :; do
	case "$1" in
		-j|--jobs) hasher_jobs=$2; shift
			;;
		-d|--drop) rapid_drop_mode=1
			;;
		-h|--help) show_help
			;;
		--) shift; break
			;;
		*) echo "Error parsing arguments. see --help" ; exit 1
			;;
	esac
	shift
done

if [ -z "$hasher_jobs" ]; then
    echo "Please, specify a number of jobs to run in parallel (-j option)"
    exit 1
fi

. autorepo-sh-functions
autorepo_lock_workdir_or_exit

OUTDIR=$AUTOREPO_HOME/OUT
[ -d OUT ] && OUTDIR=OUT
if [ ! -d $OUTDIR ]; then
    echo "ERROR: dir $OUTDIR not found."
    exit 1
fi

shopt -s nullglob
ls $OUTDIR/*.{src.rpm,tar,transaction} | parallel -j$hasher_jobs \
    autorepo-helper-do-atomic-build --number {%} ${rapid_drop_mode:+--drop} {}

autorepo_unlock_workdir_safe
