#!/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>
  -K,--keep-hasher-cache keep hasher cache after build
  -C,--use-hasher-cache	create hasher used as cache to be hardlinked to save space in /tmp
  -d,--drop	drop package at first unsuccessful build
  -r,--rm-good	remove built pkgs from INDIR
  -h, --help	show this text and exit.

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

use_hashercache=
keep_hashercache=
rapid_drop_mode=
rm_good_from_indir=
. autorepo-build-config
hasher_jobs=$AR_BUILDER_DEFAULT_PARLLEL_JOBS

TEMP=`getopt -n $PROG -o Cdj:Krh -l jobs:,drop,keep-hasher-cache,no-keep-hasher-cache,rm-good,no-rm-good,use-hasher-cache,no-use-hasher-cache,help -- "$@"` ||
	show_help
eval set -- "$TEMP"

while :; do
    case "$1" in
	-j|--jobs) hasher_jobs=$2; shift
		;;
	-C|--use-hasher-cache) use_hashercache=1
		;;
	-K|--keep-hasher-cache) keep_hashercache=1
		;;
	--no-use-hasher-cache) use_hashercache=
		;;
	--no-keep-hasher-cache) keep_hashercache=
		;;
	-d|--drop) rapid_drop_mode=1
		;;
	-r|--rm-good) rm_good_from_indir=1
		;;
	--no-rm-good) rm_good_from_indir=
		;;
	-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

. parentlock-sh-functions
# remove if use your own trap
parentlock_set_unlock_workdir_trap_on_int_term_exit
parentlock_lock_workdir_or_exit

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

if ! stat -t "$INDIR"/* >/dev/null 2>&1; then
    echo "$INDIR is empty, nothing to do."
    exit 0
fi

if [ -n "$use_hashercache" ]; then
    autorepo-buildhelper-prepare-parallel-build ${keep_hashercache:+--keep-hasher-cache}
fi

# DANGER! if INDIR is empty, it is just ls [$HOME] | piped
# thus we need a check above.
shopt -s nullglob

ls $INDIR/*.{src.rpm,tar,transaction} | parallel --will-cite -j$hasher_jobs \
    autorepo-buildhelper-do-atomic-build ${use_hashercache:+--use-hasher-cache} --number {%} ${rapid_drop_mode:+--drop} {}

# CLEANUP of hashers; call always
autorepo-buildhelper-done-parallel-build ${keep_hashercache:+--keep-hasher-cache}

[ -z "$rm_good_from_indir" ] || autorepo-buildhelper-rm-good-from-out

parentlock_unlock_workdir_safe
