#!/bin/sh -efu

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

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

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

FORPOCKET=
if [ "${1-}" = '-p' ]; then
	FORPOCKET=1; shift
fi

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

if [ -n "$FORPOCKET" ]; then
	umask 0002
	pocket="$(validate_pocket_name "$1")"
	repo=$(cat $GIRAR_POCKETS/$pocket/files/pocket/repo)
else
	set_repo "${1-}"
fi

cd "$GB_TASKS"

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

cd index/"$repo"/new ||
	fatal "index tree for '$repo' is not available"
cd - >/dev/null

# 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))

[ -n "$FORPOCKET" ] &&
logger -t "$PROG" "user=$GIRAR_USER task=$id repo=$repo pocket=$pocket" ||
logger -t "$PROG" "user=$GIRAR_USER task=$id repo=$repo"

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
touch "$id"/task/state "$id"/task/run
girar-task-change-state "$id" NEW
chmod g+w -- "$id"/task/state "$id"/task/run
chmod g+rws,o+t -- "$id"/task "$id"

if [ -n "$FORPOCKET" ]; then
	printf '%s\n' "$pocket" >"$id"/task/pocket
	echo >&2 "new task #$id: owner=$GIRAR_USER repo=$repo pocket=$pocket"
else
	echo >&2 "new task #$id: owner=$GIRAR_USER repo=$repo"
fi
printf '%s\n' "$id"
