#!/usr/bin/env python

import getpass
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])

username = getpass.getuser()

repo = git.repo.Repo(abspath)
def _build_commit(rev):
    old, rev, branch = rev
    branch = '/'.join(branch.split('/')[2:])
    commit = repo.rev_parse(rev=rev)

    # We just don't handle these
    if isinstance(commit, git.TagObject):
        return None

    return dict(
        name=commit.author.name,
        email=commit.author.email,
        username=username,
        summary=commit.summary,
        message=commit.message,
        stats=dict(
            files=commit.stats.files,
            total=commit.stats.total,
        ),
        rev=rev,
        path=abspath,
        repo=repo_name,
        branch=branch,
        agent=os.getlogin(),
    )

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:

    if commit is None:
        continue

    fedmsg.publish(
        # Expect this to change to just "receive" in the future.
        topic="receive",
        msg=dict(commit=commit),
        modname="git",
    )
