#!/bin/bash
# gowork-snapshot - find out installed go packages and produce buildout code to install them pinned

# FIXME currently works only with cwd=gowork/src

echo "# Code generated by gowork-snapshot; DO NOT EDIT."

# list installed go git repositories.
#
# this gives something like:
# github.com/cznic/strutil  https://github.com/cznic/strutil    529a34b1c1
# golang.org/x/net          https://go.googlesource.com/net     1087133bc4
# ...
gogit_list() {
    find . -name .git | sort | \
    while read repo; do
        importpath=${repo#./}
        importpath=${importpath%/.git}
        echo -ne "${importpath}\t"
        echo -ne "`git_upstream_url $repo`\t"
        git -C $repo describe --long --always --abbrev=10
    done
}

# git_upstream_url <repo>   - show current branch upstream URL
git_upstream_url() {
    repo=$1
    head="`git -C $repo symbolic-ref -q --short HEAD`"            # current branch - e.g. "master"
    if [ -z $head ] ; then
        remote="origin" # If we are in detached HEAD, assume the upstream name is origin
    else
        remote="`git -C $repo config --get branch.$head.remote`"  # upstream name, e.g. "origin"
    fi
    url="`git -C $repo config --get remote.$remote.url`"          # upstream URL
    if [ -z $url ] ; then
        echo "ERROR: Failed to guess upstream url from $repo" 1>&2
    fi
    echo "$url"
}

# buildout_safe <name>  - canonicalize name to be allowed to be used in buildout section name
# e.g. aaa/bbb -> aaa_bbb
#
# XXX can't use e.g. "go!lab.nexedi.com/kirr/neo" because buildout disallows
# "!" or "/" in section name references.
buildout_safe() {
    # see _simple regex in slapos.buildout
    echo -n "$1" | tr --complement -- "-a-zA-Z0-9 ._" _
}

echo
echo "# list of go git repositories to fetch"
echo "[gowork.goinstall]"
echo "depends_gitfetch  ="

gogit_list | \
while read pkg _ _; do
        echo "    \${go_`buildout_safe $pkg`:recipe}"
done

echo
gogit_list | \
while read pkg url rev; do
    echo
    echo "[go_`buildout_safe $pkg`]"
    echo "<= go-git-package"
    echo "go.importpath = $pkg"
    echo "repository    = $url"
    echo "revision      = $rev"
done
