#!/bin/sh -efu

. gb-sh-functions

id="$1"; shift

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

if [ "$(cat task/state)" != COMMITTING ]; then
	echo >&2 "Task #$id is not selected for commit"
	exit 1
fi

if [ -f task/test-only ]; then
	echo >&2 "Task #$id is a test only task"
	exit 1
fi

try=$(cat task/try)
iter=$(cat task/iter)
log="logs/events.$try.$iter.log"

(
	exec >>"$log" 2>&1

	gb-task-validate-state pending || exit 0

	# Obtain an exclusive lock on the $GB_REPO_DIR.
	if ! builtin lockf -n "$GB_REPO_DIR"; then
		stamp_echo "waiting for an exclusive lock on ${GB_REPO_DIR##*/}"
		builtin lockf -v "$GB_REPO_DIR"
		stamp_echo "acquired an exclusive lock on ${GB_REPO_DIR##*/}"
	fi

	gb-task-validate-state pending || exit 0

	stamp_echo 'task is ready for commit'

	gb-task-commit-repo
	gb-task-commit-arepo
	gb-task-commit-girar
	gb-task-commit-acl
	gb-task-repo-sync
)

rc=$?
if [ "$(cat task/state)" != COMMITTING ]; then
	exit $rc
fi

if [ "$rc" = 0 ]; then
	state=DONE
else
	state=FAILED
	halt_build_queue ||:
fi
stamp_echo >>"$log" "task #$id for $GB_REPO_NAME $state"
gb-x-girar task-change-state "$id" "$state"

#gb-task-close-bugs ||:
gb-task-cleanup ||:
gb-task-send-email "$id"
gb-task-archive "$id"

# hook up a general archive cleanup
gb-y-archive-stale-tasks ||:

exit $rc
