#!/usr/bin/env python

import git
import os
import sys

import fedmsg
import fedmsg.config

# Read in all the rev information git-receive-pack hands us.
lines = [line.split() for line in sys.stdin.readlines()]

# Use $GIT_DIR to determine where this repo is.
abspath = os.path.abspath(os.environ['GIT_DIR'])
repo_name = '.'.join(abspath.split(os.path.sep)[-1].split('.')[:-1])

repo = git.repo.Repo(abspath)
def _build_commit(rev):
    old, rev, branch = rev
    branch = '/'.join(branch.split('/')[2:])
    commit = repo.rev_parse(rev=rev)
    return dict(
        name=commit.author.name,
        email=commit.author.email,
        summary=commit.summary,
        message=commit.message,
        stats=dict(
            files=commit.stats.files,
            total=commit.stats.total,
        ),
        rev=rev,
        branch=branch,
    )

commits = map(_build_commit, lines)

print "Emitting a message to the fedmsg bus."
config = fedmsg.config.load_config([], None)
config['active'] = True
config['endpoints']['relay_inbound'] = config['relay_inbound']
fedmsg.init(name='relay_inbound', cert_prefix='scm', **config)

for commit in commits:
    fedmsg.publish(
        topic="receive.%s.%s" % (repo_name, commit['branch']),
        msg=dict(commit=commit),
        modname="git",
    )
