#!/bin/sh -efu

. gb-sh-functions

cd "$GB_TASKS_DIR"

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

task_state()
{
	tr '[:upper:]' '[:lower:]' < "$1/task/state" ||:
}

rotate()
{
	local n="$1"; shift
	local state
	state="$(task_state "$n")"
	[ -n "$state" ] || return 0
	gb-x-girar task-update-queues "$n" "$state" ''
	mkdir -p "archive/$state"
	mv -- "$n" "archive/$state/"
}


find . -mindepth 3 -maxdepth 3 -path './[1-9]*/task/state' -type f -mtime +14 |
  cut -d/ -f2 |sort -rn |while read n; do
	rotate "$n"
done
