#!/bin/sh

export LC_ALL=C
repobranch="sisyphus"
gitbranch=master
force_rewrite=
localname=
while getopts b:d:fhn: opt; do
	case "$opt" in
		b) repobranch="${OPTARG:?}"
			readonly repobranch ;;
		d) gitbranch="${OPTARG:?}" 
			readonly gitbranch ;;
		n) localname="${OPTARG:?}" 
			localname=${localname%%.git}
			readonly localname ;;
		f) force_rewrite=1
			readonly force_rewrite ;;
		h) pod2usage --exit=0 "$0"; exit 0 ;;
		*) pod2usage --exit=2 "$0"; exit 2 ;;
	esac
done
shift "$((OPTIND-1))"

name="$1"
if [ -z "$name" ]; then 
    pod2usage --exit=2 "$0"; exit 2;
fi
[ -z "$localname" ] && localname="$2"
[ -z "$localname" ] && localname="$name"

commit=`git ls-remote -h git://git.altlinux.org/gears/${name:0:1}/${name}.git refs/heads/$repobranch | awk '{print $1}'`
if [ -z "$commit" ]; then
    echo "Error:$name is not a git-built package for $repobranch. commit not found."
    exit 1
fi

if [ -n "$force_rewrite" ]; then
    rm -rf "${name}.git"
elif [ -d "${name}.git" ]; then
    echo "Error: ${name}.git already exists."
    exit 1
fi

git clone "git://git.altlinux.org/gears/${name:0:1}/${name}.git" "${localname}.git"
if [ ! -d "${localname}.git" ]; then
    echo "Error: ${localname}.git is not cloned!"
    exit 1
fi
pushd "${localname}.git"
git branch -D "$gitbranch" 2>/dev/null
git checkout -b "$gitbranch" $commit
popd

: <<'__EOF__'

=head1	NAME

girar-clone-build-commit - clone git.alt:/gears/ repository

=head1	SYNOPSIS

B<girar-clone-build-commit>
[B<-h>] 
[B<-f>] 
[B<-b> I<repository>]
[B<-d> I<local destination branch>]
[B<-n> I<local repository name>]
I<name> [I<local repository name>]

=head1	DESCRIPTION

B<girar-clone-build-commit> clone git.alt:/gears/../name.git repository
and place last build commit into local destination branch.

=head1	OPTIONS

=over

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

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

=item	B<-d> I<local destination branch name>

Name of the checked out branch. Default is master.

=item	B<-f>

Forcefully remove previous <name>.git and clone over even if <name>.git already exists.

=item	B<-h>

Display this help and exit.

=item	B<-n> I<local repository name>

Name of the local repository. Default is <name>.
Can also be specified as the second argument.

=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__
