#!/bin/sh -efu

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

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

ls_user="-user $USER_PREFIX$GIRAR_USER"
ls_recent=
done=
topdir="$GB_TASKS"
while [ "$#" -gt 0 ]; do
	case "${1-}" in
		--help) usage ;;
		--all) ls_user=; shift ;;
		--done) ls_recent='-mtime -3'
			done=' done'
			topdir="$GB_TASKS/archive/done"; shift ;;
		*) break;;
	esac
done

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

cd "$topdir"

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)
		if [ 0 = "$(cat task/rc 2>/dev/null)" ]; then
			if [ -f task/test-only ]; then
				printf ' TESTED'
			else
				printf ' DONE'
			fi
		else
			printf ' FAILED'
		fi
		;;
	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 ||:
	if [ -f task/test-only ]; then
		printf ' [test-only]'
	fi
	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 1 -maxdepth 1 -name '[1-9]*' -type d $ls_recent $ls_user -printf '%f\n' |
	sort -nr)"

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

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