#!/bin/sh -efu

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

usage()
{
	[ -z "$*" ] || message "$*"
	echo >&2 "usage: $PROG [<task_id>]"
	exit 1
}

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

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

cd "$GB_TASKS"

id="$(PROG="$PROG" girar-task-find-current "$@")"
cd "$id"

enable -f /usr/lib/bash/lockf lockf
# obtain an exclusive lock on the TASKS structure
builtin lockf -v .

if [ 'root' != "$GIRAR_USER" ]; then
	owner="$(cat task/owner)"
	[ "$owner" = "$GIRAR_USER" ] ||
		fatal "task #$id belongs to $owner"
fi

[ -n "$(find acl -mindepth 1 -maxdepth 1 -path 'acl/[1-9]*' -type d 2>/dev/null)" ] ||
	fatal "cannot run empty task #$id"

seq=
if [ -f task/seq ]; then
	seq=$(cat task/seq)
	case "$(($seq%3))" in
		# awaiting for build
		0) fatal "task #$id already scheduled for run" ;;
		# work in progress
		1) fatal "task #$id is a work in progress" ;;
		# have build results
		2)
		if [ 0 = "$(cat task/rc)" ]; then
			fatal "task #$id is already successfully processed"
		fi
		seq=$(($seq+1)) ;;
	esac
else
	seq=0
fi

try="$((1+$seq/3))"
[ $try -gt 1 ] || try=

# create group writable directories for build results
mkdir -pm3775 build plan

# create group writable files required for build
(umask 002; touch task/log"${try:+.$try}" task/rc task/seq task/summary) || false

trap '' HUP INT QUIT PIPE TERM
printf '%s\n' "$seq" >task/seq

echo >&2 "task #$id: ${try:+try=$try }queued, result will be emailed to $(cat task/owner)@$EMAIL_DOMAIN"
