#!/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>]} <modules_source> <kernel_flavour> <module_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 3 ]; then
	usage "not enough arguments"
fi

dir="$1"; shift
flavour="$1"; shift

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
	module="$1"; shift
	girar-task add "$id" kmod "$dir" "$flavour" "$module"
done

girar-task run $test_only "$id"
