#!/bin/bash

export LC_ALL=C
repobranch="sisyphus"
verbose=1
while getopts b:hqv opt; do
	case "$opt" in
	    b) repobranch="${OPTARG:?}"
		readonly repobranch ;;
	    h) pod2usage --exit=0 "$0"; exit 0 ;;
	    q) verbose=0 ;;
	    v) verbose=2 ;;
	    *) pod2usage --exit=2 "$0"; exit 2 ;;
	esac
done
shift "$((OPTIND-1))"
name="$1"
if [ -z "$name" ]; then
    pod2usage --exit=2 "$0"; exit 2;
fi
commit=`git ls-remote -h git://git.altlinux.org/gears/${name:0:1}/${name}.git refs/heads/$repobranch 2>/dev/null`
GITRETVAL=$?
if [ $GITRETVAL -eq 0 ] && [ -n "$commit" ]; then
    echo git
    exit 0;
fi
commit=`git ls-remote -h git://git.altlinux.org/srpms/${name:0:1}/${name}.git refs/heads/$repobranch 2>/dev/null`
SRPMRETVAL=$?
if [ $SRPMRETVAL -eq 0 ] && [ -n "$commit" ]; then
    echo srpm
    exit 1;
fi
if [ $GITRETVAL -eq 0 ] && [ $SRPMRETVAL -eq 0 ]; then
    [ $verbose -ge 2 ] && echo "info: $name is present in both git and srpm build history." >&2
elif [ $GITRETVAL -ne 0 ] && [ $SRPMRETVAL -eq 0 ]; then
    [ $verbose -ge 2 ] && echo "info: $name is present in srpm build history." >&2
elif [ $GITRETVAL -eq 0 ] && [ $SRPMRETVAL -ne 0 ]; then
    [ $verbose -ge 2 ] && echo "info: $name is present in git build history." >&2
elif [ $GITRETVAL -ne 0 ] && [ $SRPMRETVAL -ne 0 ]; then
    [ $verbose -ge 1 ] && echo "warning: $name not found at git.altlinux.org." >&2
fi
echo srpm
exit 1;

: <<'__EOF__'

=head1	NAME

girar-get-upload-method - get girar upload method (srpm or gear) for a package.

=head1	SYNOPSIS

B<girar-get-upload-method>
[B<-b> I<repository>]
[B<-h>] 
[B<-q>] 
[B<-v>] 
I<name>

=head1	DESCRIPTION

B<girar-get-upload-method> I<name> returns string srpm if package can be uploaded as srpm
or the string 'gear' otherwise.
Also, warning is printed to stderr if name not found at git.altlinux.org.

=head1	OPTIONS

=over

=item	B<-b> I<repository name>

Name of the repository branch. Values: sisyphus|5.1|p5|..
Default is sisyphus.

=item	B<-h>

Display this help and exit.

=item	B<-v>

Verbose. Print extra information about the package's build history.

=item	B<-q>

Quiet. Print no warnings.

=back

=head1	AUTHOR

Written by Igor Vlasenko <viy@altlinux.org>.

=head1	COPYING

Copyright (c) 2010 Igor Vlasenko, ALT Linux Team.

This 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.

=cut

__EOF__
