#!/bin/sh -efu

. girar-sh-functions

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

usage()
{
	[ -z "$*" ] || echo >&2 "$PROG: $*"
cat >&2 <<EOF
Usage: $PROG [-b <binary_repository_name>] <gear_repo_1> <gear_tag_1> ...
EOF
	exit 1
}

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

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

repo=
if [ "$1" = "-b" ]; then
	repo="$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
id="$(girar-task new "$repo")"
trap atexit EXIT

while [ $# -gt 0 ]; do
	dir="$1" tag="$2"
	shift 2
	if [ "$dir" = srpm -a -z "${tag%%*.src.rpm}" ]; then
		girar-task add "$id" srpm "$tag"
	else
		girar-task add "$id" repo "$dir" "$tag"
	fi
done

girar-task run "$id"
