#!/bin/sh -efu

# Toplevel cron select-task/run-task runner.

GB_REPO_NAME="$1"; shift
export GB_REPO_NAME

# Ensure that only one instance is running for the given repo.
lockdir="$HOME/.lockdir/$GB_REPO_NAME"
mkdir -p "$lockdir"
enable -f /usr/lib/bash/lockf lockf
builtin lockf -n "$lockdir" || exit 0
exec >> "$lockdir/log" 2>&1

# Create PID file
echo "$$" >/var/run/girar-builder/commiter-$GB_REPO_NAME.pid

# Set cwd to directory with scripts and configs.
GB_HOME="${0%/*}"
[ "$GB_HOME" != "$0" ]
cd "$GB_HOME"
export GB_HOME

# Add path to scripts to $PATH.
PATH="$PWD:$PATH"

. gb-sh-functions

atexit()
{
	kill $pid
	exit $?
}

pid=
while :; do
	# Check for global cutout switches.
	[ ! -f STOP ] || exit 0
	[ ! -f "$GB_STOP_FILE" ] || exit 0

	if [ -z "$pid" ]; then
		[ -d "$GB_TASKS_DIR/index/$GB_REPO_NAME/pending" ] ||
			mkdir -p "$GB_TASKS_DIR/index/$GB_REPO_NAME/pending"
		inotifywait -q -t 60 -e create "$GB_TASKS_DIR/index/$GB_REPO_NAME/pending" &
		pid=$!
		trap 'atexit $?' EXIT
		stamp_echo "forked $pid"
	fi
	min_iter="$(gb-y-calc-max-iter BUILDING PENDING)" ||
		min_iter=0
	[ -d "$GB_TASKS_DIR/index/$GB_REPO_NAME/committing" ] ||
		mkdir -p "$GB_TASKS_DIR/index/$GB_REPO_NAME/committing"
	stamp_echo "selecting min_iter=$min_iter"
	id="$(gb-y-select-task PENDING COMMITTING "$min_iter")" ||
		id=
	if [ -n "$id" ]; then
		stamp_echo "task $id"
		gb-commit-task "$id"
		continue
	fi
	stamp_echo waiting
	wait $pid ||
	{
		[ $? -eq 2 ] || exit
		stamp_echo timeout
	}
	pid=
done
