#!/bin/sh -efu

. girar-sh-functions

PROG=girar-clone

usage()
{
	echo >&2 "$PROG: $*"
	echo >&2 "usage: $PROG <path to git repository> [<path to directory>]"
	exit 1
}

[ "$#" -ge 1 ] ||
	usage 'Not enough arguments.'
[ "$#" -le 2 ] ||
	usage 'Too many arguments.'

[ -n "${GIRAR_HOME:-}" ] ||
	fatal 'GIRAR_HOME undefined'

[ -n "${GIRAR_ARCHIVE:-}" ] ||
	fatal 'GIRAR_ARCHIVE undefined'

cd "$HOME"

repo0="$1"; shift
repo=
p_repo="$(prefix_packages "$repo0")"
p_repo="$(add_git_suffix "$p_repo")"
if [ -e "$p_repo" ]; then
	repo="$(readlink -ev "$p_repo")/"
	people="$(readlink -ev "$GIRAR_HOME")"
	archive="$(readlink -ev "$GIRAR_ARCHIVE")"
	[ -z "${repo##$people/*}" -o -z "${repo##$archive/*}" ] ||
		fatal "$repo0: directory does not belong to allowed directory tree"
fi
if [ -z "$repo" ]; then
	case "$repo0" in
		ftp://*|git://*|http://*|https://*|rsync://*) ;;
		*) fatal "$repo0: invalid repository" ;;
	esac
fi

if [ "$#" -ge 1 ]; then
	dir0="$1"; shift
else
	dir0="${repo0##*/}"
fi

dir="$(validate_packages_dir "$dir0")"
dir="$(add_git_suffix "$dir")"
[ ! -e "$dir" ] ||
	fatal "$dir0: destination already exists"

git clone --bare --template="/usr/share/girar/templates" "$p_repo" "$dir"
cd "$dir"
echo "${dir%.git}" >description
install -m600 /dev/null git-daemon-export-ok
GIT_DIR=`/bin/pwd`
export GIT_DIR
exec "/usr/share/girar/hooks/post-update"
