#!/usr/local/bin/python3.14
# encoding: utf-8

"""
Copyright 2013 Aurélien Gâteau <agateau@kde.org>

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holders.
"""

from __future__ import print_function

import sys
import json
import os
import subprocess
try:
    from urllib.request import urlopen
    from urllib.error import HTTPError
except ImportError:
    from urllib2 import urlopen, HTTPError
    input = raw_input

from argparse import ArgumentParser

RB_URL = "https://git.reviewboard.kde.org"

DEBUG_JSON = "DEBUG_JSON" in os.environ

def retrieve_text(url):
    data = urlopen(url).read()
    if type(data) != str:
        data = data.decode('utf8')
    return data


def api_request(url):
    if DEBUG_JSON:
        print("DEBUG_JSON: Fetching", url)
    data = retrieve_text(url)
    dct = json.loads(data)
    if DEBUG_JSON:
        print("DEBUG_JSON:")
        print(json.dumps(dct, sort_keys=True, indent=4))
    return dct


def git(*args):
    cmd = ["git"] + list(args)
    print("Running '%s'" % " ".join(cmd))
    return subprocess.call(cmd) == 0


class RBClientError(Exception):
    pass


class RBClient(object):
    def __init__(self, url):
        self.url = url

    def get_request_info(self, request_id):
        try:
            dct = api_request(self.url + "/api/review-requests/%d/" % request_id)
        except HTTPError as exc:
            if exc.code == 404:
                raise RBClientError("HTTP Error 404: there is probably no request with id %d." % request_id)
            raise

        return dct["review_request"]

    def get_author_info(self, submitter_url):
        dct = api_request(submitter_url)
        return dct["user"]

    def download_diff(self, request_id):
        return retrieve_text(self.url + "/r/%d/diff/raw/" % request_id)


def parse_author_info(author_info):
    def loop_raw_input(prompt):
        while True:
            out = input(prompt)
            if out:
                return out
            print("Invalid value.")

    fullname = author_info.get("fullname")
    email = author_info.get("email")
    username = author_info["username"]
    if fullname is None:
        fullname = loop_raw_input("Could not get fullname for user '%s'. Please enter it: " % username)
    if email is None:
        email = loop_raw_input("Could not get email for user '%s'. Please enter it: " % username)
    return fullname, email


def write_patch(fl, fullname, email, summary, description, diff):
    author = "%s <%s>" % (fullname, email)
    print("From:", author, file=fl)
    print("Subject:", summary, file=fl)
    print(file=fl)
    print(description, file=fl)
    print("---", file=fl)
    print(file=fl)
    fl.write(diff)


def detect_p_value(diff):
    for line in diff.splitlines():
        if line.startswith("diff --git a/"):
            return 1
        elif line.startswith("diff --git "):
            return 0
    return 1


def main():
    parser = ArgumentParser()
    parser.add_argument("request_id", type=int,
                        help="reviewboard ID to apply")
    parser.add_argument("-b", "--branch",
                        action="store_true", dest="branch", default=False,
                        help="create a branch named after the reviewboard ID")
    args = parser.parse_args()

    request_id = args.request_id

    rb = RBClient(RB_URL)

    print("Fetching request info")
    try:
        request_info = rb.get_request_info(request_id)
    except RBClientError as exc:
        print(exc)
        return 1
    author_info = rb.get_author_info(request_info["links"]["submitter"]["href"])
    summary = request_info["summary"]
    description = request_info["description"]
    description += "\n\nREVIEW: " + str(request_id)
    for bug_closed in request_info["bugs_closed"]:
        description += "\nBUG: " + bug_closed
    fullname, email = parse_author_info(author_info)

    print("Downloading diff")
    diff = rb.download_diff(request_id)

    name = "rb-%d.patch" % request_id
    print("Creating %s" % name)
    with open(name, "w") as fl:
        write_patch(fl, fullname, email, summary, description, diff)

    if args.branch:
        if not git("checkout", "-b", "rb-%d" % request_id):
            return 1

    p_value = detect_p_value(diff)

    if not git("am", "-p%d" % p_value, name):
        return 1

    return 0

if __name__ == "__main__":
    sys.exit(main())
# vi: ts=4 sw=4 et
