#!/bin/sh -eu
#
# Quick commandline tool for adding remotes on github
#
# Steps for use:
#
# Once per computer or user, depending on location:
#     Place this in the system directory shown by `git --exec-path` or in any
#     directory listed on your $PATH, typically including $HOME/bin
#
#     You can (re)name it what you like, except that the name must begin
#     "git-".
#
# Once for each clone:
#     Configure the github project, e.g.,
#         git config github.project linuxcnc/linuxcnc
#
# To add a remote where the project name matches,
#     git remote-add-github jepler
# will add https://github.com/jepler/linuxcnc as remote 'jepler'.  It will
# also add the corresponding push URL, regardless of whether you have push
# permissions on that fork.
#
# If the name doesn't match, just include a slash.  In this case you may
# also prefer to specify a different short name as the first argument:
#     git remote-add-github mk machinekit/machinekit
#
# The remote is fetched immediately after it is added.  If an error occurs,
# you will need to 'git remove $remotename' before invoking
# 'git remote-add-github' again with corrected arguments.

# License: CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
#          Also commonly called "Public Domain"

usage () {
    echo "${0##*/}: Add a remote on github"
    sed -ne '2,/^$/s/^# \?//p' "$0" 
    exit ${1-1}
}

case "$#" in
1|2) ;;
*) usage ;;
esac

case "$1" in
-h|-help|-[?]) usage 0 ;;
esac

remotename="$1"
remotepath="${2-$1}"
project="`git config github.project || true`"
case "$remotepath" in
*/*) ;;
*)   remotepath=$remotepath/${project#*/} ;;
esac

git remote add $remotename https://github.com/${remotepath}
git remote set-url --push $remotename git@github.com:${remotepath}.git
git fetch $remotename
