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

[ -O "$id" -a -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"

state=$(cat "$id"/task/state)
case "$state" in
	NEW|AWAITING|EPERM|TESTED|PENDING|POSTPONED|FAILED)
		;;
	BUILDING|COMMITTING)
		fatal "task #$id is a work in progress" ;;
	DONE)
		fatal "task #$id is already successfully processed" ;;
	*)
		fatal "task #$id is in unrecognized state \"$state\"" ;;
esac

logger -t "$PROG" "user=$GIRAR_USER task=$id state=$state"

echo >&2 -n "removing task #$id ... "
girar-task-update-queues  "$id" "$state" ''
rm -rf -- "$id"/
echo >&2 done
