#!/usr/bin/env bash
#
# Clone a remote GIT repository.
# Copyright (c) Petr Baudis, 2005
#
# This is like cg-init, but it will create a new directory where it will do
# the checkout.
#
# Takes a parameter specifying the location of the source repository and an
# optional second parameter specifying the destination. If the second
# parameter is omitted, the basename of the source repository is used as the
# destination.
#
# OPTIONS
# -------
# -l::
#	Symlink the object database when cloning locally, instead of
#	hardlinking all the objects. This is suitable for very fast
#	cloning of arbitrarily big repositories, but might be a trouble
#	in multi-user environments, and less solid arrangement in case
#	you do dangerous things with the database. Also, disappeared
#	or moved origin repository will obviously render this one unusable
#	as well. The choice is yours.
#	Note that you MUST NOT prune repository containing a symlink
#	or being symlinked to.
# -s::
#	Clone in the current directory instead of creating a new one.
#	Specifying both -s and a destination directory makes no sense.

USAGE="cg-clone [-l] [-s] LOCATION [DESTDIR]"
_git_repo_unneeded=1

. ${COGITO_LIB}cg-Xlib || exit 1

same_dir=
symlink=
while optparse; do
	if optparse -l; then
		symlink=1
	elif optparse -s; then
		same_dir=1
	else
		optfail
	fi
done

location=${ARGS[0]}

[ "$location" ] || usage
location=${location%/}

destdir=${ARGS[1]}
if [ "$destdir" ]; then
	[ ! "$same_dir" ] || die "specifying both -s and DESTDIR makes no sense"
	dir=$destdir
else
	dir=${location%#*}; dir=${dir%/.git}; dir=${dir##*/} dir=${dir%.git}
fi

if ! echo "$location" | grep -q ":" ; then
	location=$(echo "$location" | sed -e "s#^[^/]#$(pwd)\/&#")
else
	[ ! "$symlink" ] || die "specifying -l for non-local clone makes no sense"
	location="$location"
fi

if [ ! "$same_dir" ]; then
	[ -e "$dir" ] && die "$dir/ already exists"
	mkdir "$dir" || exit $?
	cd "$dir" || exit $?
else
	dir=.
fi


cleanup_trap "cd .. && rm -rf $dir"

cg-init -I || die "init failed"
if [ "$symlink" ]; then
	rmdir $_git/objects/*
	rmdir $_git/objects
	src="${location%#*}"
	[ -d "$src/.git" ] && src="$src/.git"
	ln -s $src/objects $_git/objects
fi
cg-branch-add origin "$location"
cg-fetch origin || die "fetch failed"

cp $_git/refs/heads/origin $_git/refs/heads/master &&
	git-read-tree HEAD &&
	git-checkout-index -a &&
	git-update-index --refresh ||
	exit 1

echo "Cloned to $dir/ (origin $location available as branch \"origin\")"
