#!/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_ARCHIVE:-}" ] ||
	fatal 'GIRAR_ARCHIVE undefined'

[ -n "${GIRAR_GEARS:-}" ] ||
	fatal 'GIRAR_GEARS 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")"
	gears="$(readlink -ev "$GIRAR_GEARS")"
	[ -z "${repo##$people/*}" -o \
	  -z "${repo##$archive/*}" -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

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

git clone --bare --template="$GIRAR_TEMPLATES_DIR" "$p_repo" "$dir" >/dev/null
cd "$dir"
echo "${dir%.git}" >description
install -m600 /dev/null git-daemon-export-ok
GIT_DIR="$PWD" "$GIRAR_HOOKS_DIR/post-update"
printf '%s:\t%s\n' "$PROG" "$PWD"
