#!/bin/sh -efu

. girar-sh-functions

cd "$GB_TASKS"

if [ $# -gt 0 ]; then
	id="$1"
	shift
	[ -n "$id" -a -z "$(printf %s "$id" |tr -d '[:digit:]')" ] ||
		fatal "invalid task id: $id"
else
	id="$(find . -mindepth 3 -maxdepth 3 -path './[1-9]*/task/owner' -type f -user "$USER_PREFIX$GIRAR_USER" 2>/dev/null |
		cut -d/ -f2 |
		sort -nr |
		head -n1)"
	[ -n "$id" ] ||
		fatal 'no tasks found'
fi

[ -d "$id" ] ||
	fatal "task not found: $id"
[ -s "$id"/task/owner ] ||
	fatal "invalid task: $id"

printf %s "$id"
