#!/usr/bin/python3
# Author: Brian Murray <brian@canonical.com>
# Copyright (C) 2011 Canonical, Ltd.
# License: GPLv3
#
# this is a bzr plugin that belongs in ~/.bazaar/plugins and will
# modify the bug, modify tags and unsubsribe bugcontrol,
# for which a bugpattern was written
#
# it requires the package python-launchpadlib-toolkit be installed

import os
import re

from bzrlib import branch
from bzrlib import errors
from lpltk import LaunchpadService
from subprocess import Popen, PIPE


def post_push_hook(push_result):
    lp = LaunchpadService(config={})
    bugcontrol = lp.launchpad.people['ubuntu-bugcontrol']
    bug_numbers = []
    # assumes you are in the branch directory
    try:
        wb = branch.Branch.open(os.getcwd())
    except errors.NotBranchError:
        return
    if wb.get_parent() != 'bzr+ssh://bazaar.launchpad.net/~ubuntu-bugcontrol/apport/ubuntu-bugpatterns/':
        return
    delta = wb.get_revision_delta(wb.revno())
    if 'bugpatterns.xml' not in delta.get_changes_as_text():
        return
    # can't figure out how to get the contents of the diff
    diff = Popen(["bzr", "log", "-r-1", "-p"], stdout=PIPE).communicate()[0]
    for line in diff.split('\n'):
        if not line.startswith('+'):
            continue
        if 'pattern url' in line and 'launchpad.net/bugs' in line:
            bug_number = re.search('(\d+)', line).group(1)
            bug_numbers.append(bug_number)
    for bug_number in bug_numbers:
        bug = lp.get_bug(bug_number)
        if bug.private:
            print('LP: #%s is private and should be made public' % bug_number)
        if not 'bugpattern-needed' in bug.tags:
            bug.tags.append('bugpattern-written')
            print('LP: #%s didn\'t need a bug pattern' % bug_number)
            continue
        bug.tags.remove('bugpattern-needed')
        bug.tags.append('bugpattern-written')
        bug.lpbug.unsubscribe(person=bugcontrol)
        print('LP: #%s modified by bug pattern written bzr hook' % bug_number)

branch.Branch.hooks.install_named_hook('post_push', post_push_hook,
    'Bug pattern written hook')
