#!/bin/sh

# load common functions, compatible with local and installed script
. `dirname $0`/../share/eterbuild/functions/common
load_mod git

test -r "$1" && fatal "Do not need any files in params"

PUSHFORCE=
PUSHALL=
TAGSALL=
NEWGIRAR=

#############################
Usage="Usage: $name [GIRAR/remote alias] [-f|--force] [-a|--all] [-t|--tags] [tag]"
function mygetopts()
{
name=${0##*/}
Descr="$name - publish current project repo remote git repo"

phelp()
{
	echog "$Descr"
	echog "$Usage"
	echog "Options:"
	echog " -f - force push"
	echog " -a - push all branches"
	echog " -t - push all tags"
}

while getopts :hfat opt; do
    case $opt in
    h) phelp; exit 0;;
    f) PUSHFORCE="--force" ;;
    a) PUSHALL="--all" ;;
    t) TAGSALL="--tags" ;;
    +?) echog "$name: options should not be preceded by a '+'." 1>&2; exit 2;;
    ?) OPTIND=$((OPTIND-1)); break;
    esac
done

## remove args that were options
if [ $# -gt 0 ]; then
	shift $((OPTIND - 1))
fi

LISTARGS="$@"
#LISTARGS=$(drop_args "$*" f a t)

}

# Skip first param
if ! echo "$1" | grep -q "^-" ; then
    NEWGIRAR="$1"
    shift
fi

mygetopts $@


push_to_remote()
{
	local GHOST=$1
	local TEXTTAG=
	local PROJECTNAME=$(pwd)/$(get_gear_name)

	[ -n "$TAGSALL$PUSHALL" ] && TEXTTAG="(with all tags)"

	echo
	echo "** Push $TEXTBRANCH from $PROJECTNAME.git to $GHOST $TEXTTAG"

	git push $PUSHALL $PUSHFORCE $GHOST $CURRENTBRANCH || return
	[ -z "$TAGSALL" ] || git push --tags $GHOST $CURRENTBRANCH
}

tune_girarlist()
{

REMOTELIST="$(get_remote_git_list)"

if [ -z "$NEWGIRAR" ] ; then
	NEWGIRAR="$1"
	shift
fi

# If run with gear as param
if [ -n "$NEWGIRAR" ] ; then
	# if run with girar host in arg
	if is_girar_name "$NEWGIRAR" ; then
		# if remote list is empty, do ginit
		[ -n "$REMOTELIST" ] || ginit $NEWGIRAR
	fi
	LISTGIRARHOST="$NEWGIRAR"
else
	# use one target if it one
	if is_one_girar_name "$REMOTELIST" ; then
		GIRARHOST="$REMOTELIST"
	fi

	# origin by default if exists and alone
	if get_remote_repo_list | grep -q origin ; then
		GIRARHOST="origin"
	fi
	LISTGIRARHOST="$GIRARHOST $(do_exclude_list "$GIRARHOST" "$REMOTELIST")"
fi

# if set it can be tag or branch name
if [ -n "$1" ] ; then
	CURRENTBRANCH="$1"
	shift
else
	CURRENTBRANCH=$(get_current_branch)
fi

[ -n "$CURRENTBRANCH" ] || fatal "Can't detect current branch"

}

tune_girarlist $LISTARGS

if [ "$PUSHALL" = "--all" ] ; then
	TEXTBRANCH="all branches"
	CURRENTBRANCH=
else
	TEXTBRANCH="branch $CURRENTBRANCH"
	if git tag | grep -q "^$CURRENTBRANCH\$" ; then
		TEXTBRANCH="tag $CURRENTBRANCH"
	fi
fi

for i in $LISTGIRARHOST ; do
	push_to_remote $i
done
