#!/bin/bash
#
# replace gist git repo remote origin https URL with SSH one.
#

if [[ "$1" = "-p" ]]; then
    pull=1
    shift
fi

for d in *; do
    if [ -d "$d/.git" ]; then
        pushd "$d"
        url="$(git remote get-url origin)"
        newurl="$(echo $url | sed -e 's|https://|git@|;s|\.com/|.com:|')"

        if [ "x$url" != "x$newurl" ]; then
            git remote set-url origin "$newurl"
        fi

        branch="$(git branch --show-current)"
        tracking="$(git config branch.$branch.merge)"

        if [ -z "$tracking" ]; then
            git branch --set-upstream-to=origin/$branch $branch
        fi

        if [[ "$pull" -eq 1 ]]; then
            git pull
        fi

        popd
    fi
done