#!/bin/sh -efu

. girar-sh-functions
PROG='girar-task new'

usage()
{
	[ -z "$*" ] || message "$*"
	cat >&2 <<EOF
usage: $PROG [<binary_repository_name>]
Valid repositories are: $(tr -s '\n' ' '<"$GIRAR_REPOSITORIES")
EOF
	exit 1
}

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

if [ "$#" -gt 1 ]; then
	usage 'Too many arguments.'
fi

repo="$(printf %s "${1:-sisyphus}" |tr '[:upper:]' '[:lower:]')"
fgrep -ixqse "$repo" "$GIRAR_REPOSITORIES" ||
	fatal "invalid repository \`$repo', valid repositories are: $(tr -s '[:space:]' ' '<"$GIRAR_REPOSITORIES")"

cd "$GB_TASKS"

[ -w .max-task-id ] ||
	fatal 'Permission denied'

# dumb protection against frequent runs
sleep 1

enable -f /usr/lib/bash/lockf lockf
# obtain an exclusive lock on $GB_TASKS
builtin lockf -v .

id=$(cat .max-task-id)
id=$(($id+1))

trap '' HUP INT QUIT PIPE TERM
printf '%s\n' "$id" >.max-task-id

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

mkdir "$id"
# obtain an exclusive lock on the TASKS structure
builtin lockf -v "$id"
trap atexit EXIT
mkdir "$id"/task
printf '%s\n' "$id" >"$id"/task/id
printf '%s\n' "$GIRAR_USER" >"$id"/task/owner
printf '%s\n' "$repo" >"$id"/task/repo

echo >&2 "new task #$id: owner=$GIRAR_USER repo=$repo"
printf '%s\n' "$id"
