#!/bin/bash
pname="$(basename "$0")"

function usage(){
   printf "%s usage:\n" "$pname"
   printf "   %s [-a|--add \$NAME] \$USER_HOST \$REMOTE_REPOSITORY_DIRECTORY\n\n" "$pname"
   printf "If a remote \$NAME is specified, then a secondary remote with that name is added.\n\n"
}

remote='origin'
uhost=''
repository=''

case "$1" in
-a|--add)
    shift
    if [ $# -ne 3 ] ; then
        usage
        exit 1
    fi
    remote="$1"
    shift
    ;;
*)
    if [ $# -ne 2 ] ; then
        usage
        exit 1
    fi
    ;;
esac

uhost="$1"
repository="$2"

case "$repository" in
/*)
    true
    ;;
*)
    printf "The path of the remote repository directory must be absolute.\n"
    printf "'%s' is a relative path.\n"  "$repository"
    exit 2
esac

if [ -d .git ] ; then
    true
else
    printf "The current working directory must be a local git repository.\n"
    printf "There is no .git subdirectory in '%s'.\n"  "$(pwd)"
    exit 3

fi

intr="$(stty -a|tr ';' '\012'|awk '/intr/{print $3}')"
# intr="C-c"

printf "Will create a remote repository on ssh://%s%s\n" "$uhost" "$repository"
printf "and push there the current local git repository %s\n" "$(pwd)"
printf "Please confirm (RET/%s): " "$intr"
read line

function remote(){
    local temp=$(echo /tmp/create-remote-git-repository--$(hostname -f)--$$.sh | sed -e 's/ /-/g')
    printf "$@" | ssh "$uhost" bash -c "cat > $temp ; source $temp ; rm $temp"
}

remote "mkdir -p \"%s\" && cd \"%s\" && git --bare init && touch \"%s/git-daemon-export-ok\"" "$repository" "$repository" "$repository" \
&& git remote add "$remote" "ssh://$uhost$repository" \
&& git push "$remote" master \
&& remote "cd \"%s\" && git update-server-info" "$repository"

exit 0
ViewGit