#!/usr/bin/env python3
# Copyright 2016 Kitware, Inc.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.

import json
import socket
import subprocess


def git_config(name):
    return subprocess.check_output(['git', 'config', '--get', name]).decode('utf-8')


def handle_post_receive(fin):
    updates = []
    for line in fin:
        old, new, ref = line.split()
        updates.append({
            'ref': ref,
            'old': old,
            'new': new,
        })

    name = git_config('service.project').strip()
    data = {
        'hook': 'post-receive',
        'project': name,
        'updates': updates,
    }
    sockpath = git_config('service.socket').strip()

    with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
        sock.connect(sockpath)
        sock.sendall(json.dumps(data).encode('utf-8'))
        sock.sendall(b'\0')


if __name__ == '__main__':
    import sys
    handle_post_receive(sys.stdin)
