#!/usr/bin/env python
# Originally borrowed from A. Israel's https://gist.github.com/aisrael/b2b78d9dfdd176a232b9
from __future__ import print_function
import re
import os
import argparse
import github

from git import Repo


merge_re = re.compile("Merge pull request #(\d+).*")
fixes_re = re.compile(r"Fixes\:? #(\d+)")
tracker_re = re.compile("http://tracker.ceph.com/issues/(\d+)")
signed_off_re = re.compile("Signed-off-by: (.+) <")


def make_release_notes(gh, repo, ref):

    for commit in repo.iter_commits(ref):
        merge = merge_re.match(commit.summary)
        if merge:
            pr = {}
            issue = ''
            pr = gh.repos("ceph")("ceph").pulls(merge.group(1)).get()
            # We are not handling multiple issues here yet
            if pr['body']:
                fixes = fixes_re.findall(pr['body'])
                tracker = tracker_re.findall(pr['body'])
                if tracker:
                    issue = ','.join(tracker)
                elif fixes:
                    issue = ','.join(fixes)

            title = pr['title']

            # Big assumption, do a sanity check in the end, we are
            # getting the author of final merge commit
            author = commit.parents[-1].author.name
            if issue:
                print ("{0}(#{1}, {2})".format(title, issue, author))
            elif author:
                print ("{0}({1})".format(title, author))
            else:
                print (title)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--rev", "-r",
                        help="git revision range for creating release notes")
    parser.add_argument("repo", metavar="repo",
                        help="path to ceph git repo")
    parser.add_argument("--token", default=os.getenv("GITHUB_ACCESS_TOKEN"),
                        help="Github Access Token ($GITHUB_ACCESS_TOKEN otherwise)")

    args = parser.parse_args()
    gh = github.GitHub(
        access_token=args.token)

    make_release_notes(gh, Repo(args.repo), args.rev)
