#!/usr/bin/env bash
{ set +x; } 2>/dev/null

usage() {
    echo "usage: $(basename $0) [path ...]" 1>&2
    [ "$1" = "-h" ] || [ "$1" = "--help" ]; exit
}

[ "$1" = "-h" ] || [ "$1" = "--help" ] && usage "$@"

while [[ $# != 0 ]]; do
    cd "$1" || exit
    shift
    ! [ -e .git ] && continue
    ! [ -e .git/config ] && continue
    url="$(git remote -v | grep gist.github.com | head -1 | awk '{print $2}')"
    [[ -z "$url" ]] && continue

    # https://gist.github.com/<id>.git
    [[ "$url" == "https"* ]] && {
        echo "$url" | awk -F":" '{print $2}' | sed 's/.\{4\}$//' && continue
    }
    # git@gist.github.com:<id>.git
    [[ "$url" == "git@"* ]] && {
        echo "$url" | awk -F":" '{print $2}' | sed 's/.\{4\}$//' && continue
    }
    echo "ERROR: $url" 1>&2 && exit 1
done;:
