#!/usr/bin/env python
#
# Example post-receive hook for uChoob's RCS plugin.
# Place in .git/hooks/post-receive and chmod +x
#
# Copyright (C) 2007  Chris Lamb <chris@chris-lamb.co.uk>
#
# This file is part of uChoob.
#
# uChoob is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# uChoob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with uChoob.  If not, see <http://www.gnu.org/licenses/>.


import sys
from commands import getoutput
from xmlrpclib import ServerProxy

p = ServerProxy(r'https://dev.potager.org')
project = "grenode-web"

refs = [x.strip().split(' ') for x in sys.stdin.readlines()]
for old, new, refname in reversed(refs):
    metadata, msg = getoutput('git-cat-file commit %s' % (new,)).split("\n\n", 1)

    data = {
        'msg' : msg.split("\n")[0],
        'refname' : refname.replace('refs/heads/', ''),
    }

    for line in metadata.split("\n"):
        try:
            key, value = line.split(' ', 1)
            data[key] = value
        except ValueError:
            pass

    # Get files
    data['files'] = []
    cmd = 'git-diff-tree --name-only -r %s %s' % (data['parent'], data['tree'])
    for filename in getoutput(cmd).split('\n'):
        data['files'].append(filename)

    # Strip timestamps from author
    data['author'] = ' '.join(data['author'].split(' ')[:-2])

    try:
        p.commit(data['author'], data['refname'], new[:10], data['files'], data['msg'], project)
    except Exception, e:
        print >>sys.stderr, e
        break
