#!/bin/sh -efu

. girar-sh-functions

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_SRPMS:-}" ] ||
	fatal 'GIRAR_SRPMS undefined'

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

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

cd

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

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

ISPROJECT=
dir="$(validate_packages_dir "$dir0")"
dir="$(add_git_suffix "$dir")"
printf %s "$dir" |egrep -qs '^/projects' &&
	ISPROJECT=1
[ ! -e "$dir" ] ||
	fatal "$dir0: destination already exists"

[ -n "$ISPROJECT" ] && umask 0002
git clone --bare --template="$GIRAR_TEMPLATES_DIR" "$p_repo" "$dir" >/dev/null ||
	fatal "$dir: failed to clone"
cd "$dir"
echo "${dir%.git}" >description
install -m600 /dev/null git-daemon-export-ok
GIT_DIR="$PWD" "$GIRAR_HOOKS_DIR/post-update"
if [ -n "$ISPROJECT" ]; then
	GIT_DIR=. git config "core.sharedRepository" "true"
	GIT_DIR=. git config "girar.merges" "false"
fi
printf '%s:\t%s\n' "$PROG" "$PWD"
