#!/usr/bin/env python

# Copyright (c) 2010 Stanford University
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
import SOAPpy
import re
import subprocess
import sys

def captureSh(command, **kwargs):
    """Execute a local command and capture its output."""

    kwargs['shell'] = True
    kwargs['stdout'] = subprocess.PIPE
    p = subprocess.Popen(command, **kwargs)
    rc = p.wait()
    if rc:
        raise subprocess.CalledProcessError(rc, command)
    output = p.stdout.read()
    if output.count('\n') and output[-1] == '\n':
        return output[:-1]
    else:
        return output

WSDLURL = captureSh('git config --get jira.wsdl')
USERNAME = captureSh('git config --get jira.username')
PASSWORD = captureSh('git config --get jira.password')

CLOSES_SYNONYMS = """
    close closes closed
    fix fixes fixed
    resolve resolves resolved
"""

CLOSES_REGEX = r'\b(?:%s)\s+(RAM-\d+)\b' % '|'.join(CLOSES_SYNONYMS.split())
AFFECTS_REGEX = r'\b(RAM-\d+)\b'

soap = None
auth = None
def login():
    global soap
    global auth
    if soap is None:
        soap = SOAPpy.WSDL.Proxy(WSDLURL)
        auth = soap.login(USERNAME, PASSWORD)

def add_comment(issue, comment):
    login()
    soap.addComment(auth, issue, {'body': comment})

def close_issue(issue):
    login()
    # workflow action 2 means closed and resolution 1 means fixed
    soap.progressWorkflowAction(auth, issue, '2',
                                [{"id": "resolution", "values": "1"}])

for line in sys.stdin:
    old, new, ref = line.split()
    if ref != 'refs/heads/master':
        continue
    # new_commits are the commits that are newly reachable from master
    new_commits = captureSh('git rev-list --reverse %s..%s' % (old, new))
    for commit in new_commits.split():
        summary = captureSh('git show --stat %s' % commit)
        # affects are all issues mentioned in the commit message.
        # closes are # all issues closed in the commit message.
        # affects is a superset of closes.
        affects = set(re.findall(AFFECTS_REGEX, summary, re.IGNORECASE))
        closes = set(re.findall(CLOSES_REGEX, summary, re.IGNORECASE))
        for issue in affects:
            add_comment(issue, '{noformat}\n%s\n{noformat}' % summary)
        for issue in closes:
            close_issue(issue)
