#!/usr/bin/env python

import sys
import ConfigParser
import getopt
import os.path
import requests
import json

# Config file path
config_path = os.path.expanduser('~/.gerrit-webhook')

config = ConfigParser.RawConfigParser()
config.read(config_path)

url = config.get('webhook', 'url')

def show_usage():
    print '\nNormal webhook usage: ' + sys.argv[0] + ' --action [new|merged|abandoned] --change <change id> --commit <git hash> --change-url <url to change>'

def fire_webhook(action, id, commit, commitUrl, who, branch, project):
    payload = {
        'action': action,
        'id': id,
        'commit': commit,
        'url': commitUrl,
        'user': who,
        'branch': branch,
        'project': project
    }
    headers = {'content-type': 'application/json'}
    requests.post(url, data=json.dumps(payload), headers=headers)

def main():
    if (len(sys.argv) < 2):
        show_usage()
        exit()

    need = ['action=', 'change=', 'change-url=', 'commit=', 'project=', 'branch=', 'uploader=',
            'patchset=', 'abandoner=', 'reason=', 'submitter=', 'is-draft=', 'change-owner=', 'author=', 'comment=', 'newrev=', 'kind=', 'Code-Review=']
    optlist, args = getopt.getopt(sys.argv[1:], '', need)
    id = action = commitUrl = who = commit = branch = project = ''

    for o, a in optlist:
        if o == '--change': id = a
        elif o == '--change-url': commitUrl = a
        elif o == '--commit': commit = a
        elif o == '--action': action = a
        elif o == '--uploader': who = a
        elif o == '--submitter': who = a
        elif o == '--abandoner': who = a
        elif o == '--branch': branch = a
        elif o == '--project': project = a

    if (len(commit) > 0 and len(id) > 0):
        fire_webhook(action, id, commit, commitUrl, who, branch, project)
    else:
        show_usage()
        
if __name__ == '__main__':
    main()
