#!/bin/sh -efu

. girar-sh-functions

[ -n "${GIRAR_USER-}" ] ||
	fatal 'GIRAR_USER undefined'

usage()
{
	[ -z "$*" ] || echo >&2 "$PROG: $*"
cat >&2 <<EOF
Usage: $PROG [--test-only] {[-b <binary_repository_name>]|[-p <pocket_repository_name>]} [--deps <deps>] <build_source_1> <build_name_1> ...
where \`<binary_repository_name>' is a valid binary package repository name,
\`<deps> is a comma-separated list of required task id numbers, and
\`<build_source> <build_name>' pair is either \`<gear_repo> <gear_tag>'
or \`srpm <srpm_file>' or \`rebuild <package_name>'
or \`del <package_name>' or \`copy <package_name>'.
EOF
	exit 1
}

if [ "${1-}" = '--help' ]; then
	usage
fi

test_only=
if [ "${1-}" = '--test-only' ]; then
	test_only=--test-only
	shift
fi

repo=
if [ "$1" = '-b' ]; then
	repo="$2"
	shift 2
fi

pocket=
if [ "$1" = '-p' ]; then
	pocket="$2"
	shift 2
fi

if [ $# -lt 2 ]; then
	usage "not enough arguments"
fi

deps=
if [ "$1" = '--deps' ]; then
	deps="$2"
	shift 2
fi

if [ $# -lt 2 ]; then
	usage "not enough arguments"
fi

if [ "$(($#%2))" -ne 0 ]; then
	usage "odd number of arguments"
fi

atexit()
{
	local rc=$?
	trap - EXIT
	[ "$rc" -eq 0 ] || girar-task rm "$id"
	exit $rc
}

trap '' HUP INT QUIT PIPE TERM
if [ -n "$pocket" ]; then
	id="$(girar-task new -p "$pocket")"
else
	id="$(girar-task new "$repo")"
fi
trap atexit EXIT

if [ -n "$deps" ]; then
	girar-task deps "$id" set $(printf %s "$deps" |tr , ' ')
fi

while [ $# -gt 0 ]; do
	dir="$1" tag="$2"
	shift 2
	case "$dir" in
		copy|del|rebuild|srpm) girar-task add "$id" "$dir" "$tag"
			;;
		*) girar-task add "$id" repo "$dir" "$tag"
			;;
	esac
done

girar-task run $test_only "$id"
