#!/bin/sh -efu
#
# Copyright (C) 2009  Alexey I. Froloff <raorn@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.
#

. girar-client-sh-functions

show_help()
{
	cat <<EOF
Usage: $PROG [Options] <user>[,<user>...] <repository> [<directory>]

$PROG clones package from others' repository and sets up remotes for every
USERs.

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

 * girar.remote, corresponding to --remote;

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

  -q,--quiet          try to be more quiet;
  -v,--verbose        print a message for each action;
  -V,--version        print program version and exit;
  -h,--help           show this text and exit.

Report bugs to http://bugs.altlinux.ru/

EOF
	exit
}

print_version()
{
	cat <<EOF
$PROG version $PROG_VERSION
Written by Alexey I. Froloff <raorn@altlinux.org>

Copyright (C) 2009  Alexey I. Froloff <raorn@altlinux.org>
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:,q,v,V,h \
             -l remote:,quiet,verbose,version,help -- "$@"` ||
	show_usage
eval set -- "$TEMP"

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

[ $# -eq 2 -o $# -eq 3 ] || show_usage

remote_users="$1" && shift
remote_path="$1" && shift
local_path="${1-}"

remote_path="$(remote_repo_path "$remote_path")"

[ -n "${remote_path##/*}" ] ||
	fatal "\`$remote_path' is absolute"

if [ -z "$local_path" ]; then
	local_path="${remote_path##*/}"
	local_path="${local_path%.git}"
fi

[ ! -e "$local_path" ] ||
	fatal "\`$local_path' already exists"

remote_user="${remote_users%%,*}"

path0="$(remote_repo_path "$remote_path" "$remote_user")"
run_remote_command clone "$path0" ||
	fatal "Unable to clone remote package \`$path0'"

git clone "$girar_remote:$remote_path" "$local_path" ||
	fatal "Unable to clone \`$girar_remote:$remote_path'"

cd "$local_path"
(IFS=,
for u in $remote_users; do
	git remote add -f "$u" "$girar_remote:$(remote_repo_path "$remote_path" "$u")"
done)
