#!/bin/sh -efu

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

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 "$@")

[ -w "$id" ] ||
	fatal "failed to remove task #$id: Permission denied"

enable -f /usr/lib/bash/lockf lockf
# obtain an exclusive lock on the TASKS structure
builtin lockf -n "$id" ||
	fatal "task #$id is locked"

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

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

echo >&2 -n "removing task #$id ... "
rm -rf -- "$id"/
echo >&2 done
