#!/bin/sh -efu

. shell-error
. girar-sh-config
PROG='girar-update-packages-list'

PACKAGES_LIST="$GIRAR_PACKAGES_LIST"

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

update_packages_list()
{
	local list="$1"
	find /people/ -path '/people/*/packages/*.git' 2>/dev/null |
		while read d; do
			girar-recent-mtime "$d" 2>/dev/null
		done > "$list"
	find /projects/ -path '/projects/*.git' 2>/dev/null |
		while read d; do
			girar-recent-mtime "$d" 2>/dev/null
		done >> "$list"
}

if [ "${1-}" = '--help' ]; then
	usage
fi

[ "$#" -le 1 ] || usage 'Too many arguments.'

enable -f /usr/lib/bash/lockf lockf
builtin lockf -v "$PACKAGES_LIST"

. girar-sh-tmpdir
pkglist="$tmpdir/list"

if [ "$#" -ge 1 ]; then
	repo_dir="$1"
	[ -d "$repo_dir" ] ||
		fatal "Repository mtime not updated, directory '$repo_dir' not exist"
	if grep -q "^$repo_dir[[:blank:]][0-9]\+\$" "$PACKAGES_LIST"; then
		recent_time=$(girar-recent-mtime "$repo_dir")
		sed "s|$repo_dir[[:blank:]][0-9]\+|$recent_time|" "$PACKAGES_LIST" > "$pkglist"
	else
		message "Repository directory '$repo_dir' is absent in packages list"
	fi
fi

[ -f "$pkglist" ] ||
	update_packages_list "$pkglist"

cp -f "$pkglist" "$PACKAGES_LIST"
