#!/bin/bash
# 2008, 2014 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_repo_name()
{
    giter print name

    # use repo dir name in other way
    #get_gear_name && return
    # get name from spec
    #build_rpms_name "$LISTNAMES"
    #PROJECTNAME=$(echo $BASENAME | filter_gear_name)
}

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

normalize_girar_name()
{
	case "$1" in
		ga|galt)
			echo "git.alt"
			;;
		ge|geter)
			echo "git.eter"
			;;
		*)
			echo "$1"
			;;
	esac
	return 0
}

# Check if $1 like git.alt or git.eter, git.something
is_girar_name()
{
	rhas "$1" "^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" ]
}

# TODO: check the same code in giter

set_gear_host()
{
	assert_var GIRARHOST
	GITHOST="$GIRARHOST"
	GEARHOST="$GITHOST"
	[ "$GEARHOST" = "git.alt" ] && GEARHOST="gear.alt"
	return 0
}


# Try autodetect GIRARHOST. Return true, if get it from arg (need for shift args)
set_girar_host()
{
	local GN=$(normalize_girar_name "$1")
	if is_girar_name "$GN" ; then
		GIRARHOST="$GN"
		set_gear_host
		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"
		set_gear_host
		return 1
	fi

	# if no default, set default GIRARHOST from ~/.ssh/config
	if [ -z "$GIRARHOST" ] ; then
		GIRARHOST=$(get_girar_host_from_ssh)
		#[ -n "$GIRARHOST" ] || fatal "Can't get default girar alias (like git.alt) from ~/.ssh/config"
	fi

	set_gear_host
	return 1
}

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

get_last_tag()
{
        git describe --abbrev=0 --tags 2>/dev/null
}

# check if tag is last commit tag (put on the last commit). if tag is missed, check with the last tag in repo
is_last_commit_tag()
{
        local TAG=$1
        test -n "$TAG" || TAG=$(get_last_tag)
        [ -n "$TAG" ] || return
        # check if the tag put on the last commit
        [ "$(git rev-parse HEAD)" = "$(git rev-parse $TAG^0 2>/dev/null)" ]
}

