#!/bin/zsh -f

# Act on the remote host, which mirrors local git repositories (same dir structure)
# -- clone, pull, gitk
# add as a `git remote host' maruskadell, with the path same as this one.

# todo: this should be just:  ssh @remote:local/ "$@".
# and aliases which uses & provide the $1 in $@


# get the remote host! from 'git remote'
# origin -> hostname

usage()
{
    cat <<EOF

usage: ${0##*/} [+-iv} [--] [ -r hostname]

-i add the local host as git-remote to the remote repo
-v invoke "git remote" to see we are added
-x invoke "gitk --all"  on the remote.
-r remote (by default $GIT_REMOTE_NAME)
-c clone the local/current repo to the remote, at the same path.
-f skip fetching also
EOF
}

TOP=$HOME
source /usr/share/mmc-shell/git-functions.sh
set_remote_name


function get_remote_path()
{
    # Strip $HOME
    local local_path=$(get_local_path $TOP)

    local remote_home=""
    #/home/michal

    remote_path=$remote_home$local_path
    echo $remote_path
}

remote_path=$(get_remote_path)
this_remote=$(hostname)

# historical:
if [ $this_remote = "optiplex-maruska" ]; then
    this_remote="optiplex"
fi

fetch_also=y

CMD="git fetch $this_remote"
while getopts :ivfhcxr: OPT; do
    case $OPT in
        f)
            fetch_also=n
            ;;
        i|+i)
            CMD="git-add-remote-mdell"
            ;;
        v|+v)
            CMD="git remote"
            ;;
        c)
            # a/b -> a
            remote_path=${remote_path%/*}
            local local_path=$(get_local_path)
            CMD="git clone $this_remote:$local_path"

            run_post=y
            ;;
        x)
            CMD="gitk --all"
            ;;
        -h)
            usage
            exit 0
            ;;
        r)
            GIT_REMOTE_NAME=$OPTARG
            ;;
        *)
            usage >&2
            exit 2
    esac
done

shift OPTIND-1
OPTIND=1
# if [ $# -lt 1 ]; then
#     usage; exit 2
# fi

#hostname=$1
#shift

set -x
ssh -Y -A $GIT_REMOTE_NAME "cd $remote_path; $CMD $@"

if [ $fetch_also = y ]; then
    git fetch $GIT_REMOTE_NAME
fi


#POSTCMD="
if [ ${run_post-n} = y ]; then
    # $CMD git remote add $GIT_REMOTE_NAME $GIT_URL:$remote_path
    git-add-remote-mdell        # -r $GIT_REMOTE_NAME
    git fetch $GIT_REMOTE_NAME
fi


# `find':
# time for-each-git-dir       --  'if git remote show e6440 &>/dev/null; then cecho blue candidate $(pwd); fi'
