#!/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>]|[-p <pocket_repository_name>]} <build_source_1> <build_name_1> ...
where \`<build_source> <build_name>' pair is either \`<gear_repo> <gear_tag>'
or \`srpm <srpm_file>' or \`del <package_name>' or \`copy <package_name>'.
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

pocket=
if [ "$1" = "-p" ]; then
	pocket="$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

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

girar-task run "$id"
