#!/bin/sh -efu
#
# Copyright (C) 2008-2009  Alexey I. Froloff <raorn@altlinux.org>
#
# girar-client common shell functions.
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#

. shell-error
. shell-quote
. shell-args

PROG="${0##*/}"
PROG_VERSION='1.5.3'

girar_config_option()
{
	local var_name="$1" opt_name="$2" def_val="$3"
	local val

	val="$(git config --get "girar.$opt_name")" ||
		val="$def_val"

	eval "$var_name=\"$(quote_shell "$val")\""
}

girar_config_option girar_remote remote 'git.alt'
girar_config_option default_date_format date-format '--rfc-3339=date'

project_name_regexp='^[A-Za-z0-9][-A-Za-z0-9_.]+$'
user_name_regexp='^[a-z][a-z_0-9]+$'

prefix_packages()
{
	local fmt='%s' dirname="${1%/*}"
	[ "$dirname" != "$1" ] ||
		fmt='packages/%s'
	printf "$fmt" "$1"
}

add_git_suffix()
{
	local arg="$1"
	[ -z "${arg##*.git}" ] ||
		arg="$arg.git"
	printf %s "$arg"
}

validate_packages_dir()
{
	local dir0 dirname dir
	dir0="$(prefix_packages "$1")"; shift
	dirname="${dir0%/*}"
	[ "$dirname" = 'packages' -o "$dirname" = 'private' -o "$dirname" = 'public' ] ||
		fatal "$dir0: invalid directory name"
	dir="$(printf %s "${dir0##*/}" |sed -e 's,/\+$,,' -e 's,\.git$,,')"
	printf %s "$dir" |egrep -qs "$project_name_regexp" ||
		fatal "$dir0: invalid directory name"
	printf %s\\n "$dirname/$dir"
}

remote_repo_path()
{
	local path="$1" && shift
	local user="${1-}"

	path="$(validate_packages_dir "$path")"
	path="$(add_git_suffix "$path")"

	if [ -n "$user" ]; then
		printf %s "$user" |egrep -qs "$user_name_regexp" ||
			fatal "$user: invalid user name"

		path="/people/$user/$path"
	fi

	printf %s\\n "$path"
}

run_remote_command()
{
	ssh "$girar_remote" "$@"
}

