#!/bin/bash
# 2008 Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Author: Denis Smirnov <mithraen@altlinux.ru>
# Public domain

get_branch_list()
{
	git branch | grep '^ ' | sed 's/^..\(.*\)/\1/'
}

get_remote_repo_list()
{
	git remote 2>/dev/null | sort -u
}

is_exist_branch()
{
	test -n "$1" || return 1
	get_branch_list | grep -q $1
}

is_exist_remote_repo()
{
	test -n "$1" || return 1
	get_remote_repo_list | grep -q $1
}

get_current_branch()
{
	git branch | grep '^\*' | sed 's/^..//' | tr -d "\n"
}

get_remote_git_list()
{
        local i
        for i in $(get_remote_repo_list) ; do
                if is_girar_name $i ; then
                        echo $i
                fi
        done
}


# Check if $1 like git.alt or git.eter, git.something
is_girar_name()
{
	echo "$1" | grep -q "^git\."
}

is_one_girar_name()
{
	local i
	local RES=""
	for i in $@ ; do
		[ -z "$RES" ] || return
		is_girar_name "$i" || return
		RES="$i"
	done
	[ -n "$RES" ]
}

# Try autodetect GIRARHOST. Return true, if get it from arg (need for shift args)
set_girar_host()
{
	if is_girar_name "$1" ; then
		GIRARHOST="$1"
		return 0
	fi

	# Try get from remote list, if unique record there
	REMOTELIST="$(get_remote_git_list)"
	if is_one_girar_name "$REMOTELIST" ; then
		# use one target if it one
		GIRARHOST="$REMOTELIST"
	fi
	return 1
}

_list_git_package()
{
	while [ -n "$1" ] ; do
		printf "%50s  " $GIRARHOST:$1
		shift
		date -d@$1
		shift
	done
}

# TODO: make world better, please
list_git_package()
{
	_list_git_package $(ssh $GIRARHOST find-package $1)
}

git_commit_ignore_nothing()
{
        git commit "$@" && return
        git commit "$@" 2>&1 | grep "nothing to commit" && return 0
        return 1
}
