#!/bin/sh -efu

. girar-sh-functions
PROG='girar-task ls'

usage()
{
	[ -z "$*" ] || message "$*"
	echo >&2 "usage: $PROG [--all]"
	exit 1
}

ls_user="-user $USER_PREFIX$GIRAR_USER"
ls_recent='-mtime -7'
case "${1-}" in
	--help) usage ;;
	--all) ls_user=; shift ;;
	--old) ls_recent=; shift ;;
esac

[ "$#" -eq 0 ] || usage 'Too many arguments.'

cd "$GB_TASKS"

enable -f /usr/lib/bash/lockf lockf

show_status()
{
	local seq try
	seq="$(cat task/seq 2>/dev/null ||:)"
	if [ -z "$seq" ]; then
		printf ' NEW'
		return
	fi
	case "$(($seq%3))" in
		# awaiting for build
		0) printf ' AWAITING' ;;
		# work in progress
		1) printf ' BUILDING' ;;
		# have build results
		2)
		[ 0 = "$(cat task/rc 2>/dev/null)" ] &&
			printf ' DONE' ||
			printf ' FAILED'
		;;
	esac
	try="$((1+$seq/3))"
	if [ $try -gt 1 ]; then
		printf ' #%s' "$try"
	fi
}

ls1()
{
	local id="$1"; shift
	cd "$id" || return
	printf '#%d' "$id"
	show_status
	if ! (builtin lockf -n . ); then
		printf ' [locked]'
	fi
	find gears -maxdepth 0 -path gears -type d -perm -g=w -printf ' [shared]' 2>/dev/null ||:
	printf ' %s' "$(cat task/repo)"
	[ -n "$ls_user" ] ||
		printf '/%s' "$(cat task/owner)"
	local i
	for i in $(gear_nums); do
		if [ -s "gears/$i/dir" ]; then
			local dir tag_name
			dir="$(cat "gears/$i/dir")"
			tag_name="$(cat "gears/$i/tag_name")"
			printf ' %s=%s' "${dir##*/}" "$tag_name"
		elif [ -s "gears/$i/srpm" ]; then
			printf ' srpm=%s' "$(cat "gears/$i/srpm")"
		elif [ -s "gears/$i/package" ]; then
			local action package
			[ -s "gears/$i/copy_repo" ] &&
				action=copy ||
				action=del
			package="$(cat "gears/$i/package")"
			printf ' %s=%s' "$action" "$package"
		fi
	done
	printf '\n'
}

ids="$(find . -mindepth 3 -maxdepth 3 -path './[1-9]*/task/owner' -type f $ls_recent $ls_user 2>/dev/null |
	cut -d/ -f2 |sort -nr)"

if [ -z "$ids" ]; then
	message "no tasks${ids:- for $GIRAR_USER}"
	exit
fi

for id in $ids; do
	(ls1 "$id")
done
