#!/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
# -------
# -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 [-s] LOCATION [DESTDIR]"
_git_repo_unneeded=1

. ${COGITO_LIB}cg-Xlib

same_dir=
if [ "$1" = "-s" ]; then
	shift
	same_dir=1
fi

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

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

if ! echo "$location" | grep -q ":" ; then
	location=$(echo "$location" | sed -e "s#^[^/]#$(pwd)\/&#")
else
	location="$location"
fi

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

trap "rm -rf $dir" SIGTERM EXIT
cg-init $location || exit $?
trap "" SIGTERM EXIT
echo "Cloned to $dir/ (origin $location available as branch \"origin\")"
