#!/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>]} <build_source_1> <build_branch_1> ...
where \`<build_source> <build_name>' pair is either \`<gear_repo> [<gear_branch>]', where default branch is master
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 1 ]; then
	usage "not enough 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

while [ $# -gt 0 ]; do
	dir="$1"; shift
	if [ $# -eq 0 ]; then
		girar-task add "$id" branch "$dir"
		break
	fi
	branch="$1"; shift
	girar-task add "$id" branch "$dir" "$branch"
done

girar-task run $test_only "$id"
