#!/bin/sh
#
# Copyright (C) 2008-2014  Etersoft
# Copyright (C) 2008-2014  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

PROGDIR=$(dirname $0)
[ "$PROGDIR" = "." ] && PROGDIR=$(pwd)

. $PROGDIR/giter-common-functions
. $PROGDIR/giter-git-functions
. $PROGDIR/giter-girar-functions

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	echo "ginit - initialize remote repo for the project from the current directory"
	echo "Use: ginit [GIRAR] [project]"
	echo "     ginit git.alt - create repo in the git.alt girar server"
	echo "     ginit rempro  - create repo rempro in [GIRAR]"
	echo "     ginit git.eter /projects/rempro  - create repo rempro in the project dir in the git.eter girar server"
	exit 0
fi

set_work_hosts $1 && shift

RPNAME="$1"
shift

test -r "$1" && fatal "Do not need any more params."

if [ -z "$RPNAME" ] ; then
	GNAME=$(get_repo_name)
	RPNAME="$GNAME"
fi

# FIXME: если не нашли, стоит взять название каталога за основу (если мы в git-репозитории)
[ -n "$RPNAME" ] || fatal "Can't detect project name. Run inside git repo, please."

# ALT Linux girar only. If there is no direct path
if ! rhas "$RPNAME" "/" ; then
	RPNAME="$(get_user_repo "$(get_girar_user)" $RPNAME)" #"
fi

# ALT Linux girar only
echo "Create remote $RPNAME repo in $GITHOST:"
if [ "$GITHOST" = "git.eter" ] ; then
	# TODO: hack until it will fixed at Etersoft's girar
	# $ ssh git.eter git-init-db /people/lav/packages/eepm.git
	# girar-init-db: /people/lav/packages/eepm.git: invalid directory name
	# at alt-init: gitery-init-db: /people/lav/packages/eepm.git: git repository already exists
	docmd ssh $GITHOST git-init-db "$(echo "$RPNAME" | sed -e "s|.*/packages|packages|g")"
else
	docmd ssh $GITHOST git-init-db "$RPNAME"
fi

if [ -n "$GNAME" ] ; then
	echo
	echo "Create $GITHOST remote repo alias:"
	docmd git remote add $GITHOST $GITHOST:$RPNAME
fi
