#!/bin/sh -fu
#
# Copyright (C) 2008 Mikhail Gusarov <dottedmag@dottedmag.net>
# Based on girar-upload (C) 2006  Alexey Gladkov <legion@altlinux.org>
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#

. gear-sh-functions
. girar-client-sh-functions

show_help()
{
    cat <<EOF
Usage: $PROG [options] <pattern> [<date format>]

$PROG searches for a git repositories matching given pattern on
git.alt. Optional date format may be supplied to format "last update"
timestamps.

Date format should be in form understandable by date(1) and defaults to RFC 3339
'date' format.

$PROG uses the git configuration file. The following variables are read:

 * girar.remote, corresponding to --remote;
 * girar.date-format, corresponding to second argument;

Arguments and options take higher priority over the configuration file values.

Options:
  -R,--remote=NAME    girar server alias, defaults to git.alt;

  -V,--version        print program version and exit;
  -h,--help           show this text and exit.

Report bugs to http://bugzilla.altlinux.org/

EOF
    exit
}

print_version()
{
    cat <<EOF
$PROG version $PROG_VERSION
Written by Mikhail Gusarov <dottedmag@dottedmag.net>

Copyright (C) 2008  Mikhail Gusarov <dottedmag@dottedmag.net>
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
EOF
    exit
}

TEMP=`getopt -n $PROG -o R:,V,h \
             -l remote:,version,help -- "$@"` ||
    show_usage
eval set -- "$TEMP"

while :; do
    case "$1" in
		-R|--remote) shift; girar_remote="$1"
		;;
        -V|--version) print_version
        ;;
        -h|--help) show_help
        ;;
        --) shift; break
        ;;
        *) fatal "unrecognized option: $1"
        ;;
    esac
    shift
done

pattern="${1-}" && shift && [ -n "$pattern" ] ||
    fatal "No pattern given"

if [ -n "${1-}" ]; then
    date_format="$1"
fi

if [ -n "${date_format-}" ]; then
    date_format="+$date_format"
else
    date_format="$default_date_format"
fi

run_remote_command find-package "$pattern" | while read repo date; do
	printf '%s\t%s\n' "$repo" "$(date -d "@$date" "$date_format")"
done
