#!/usr/bin/python
import sys
import os
import re
import shutil

from launchpadlib.launchpad import Launchpad
from argparse import ArgumentParser
from subprocess import check_output, CalledProcessError

PUSH_RE = re.compile(r'(?<=push branch: ).*$', flags=re.MULTILINE)

def _was_merged(branch):
    for merge_proposal in branch.owner.getMergeProposals(status='Merged'):
        if merge_proposal.source_branch == branch:
            return True
    return False

def main():
    parser = ArgumentParser("Scans the current directory for directories "
                            "which contain bzr branches and checks if "
                            "they are redundant - deleting them if so. ")
    args = parser.parse_args()

    lp = Launchpad.login_with(sys.argv[0], 'production', '~/.cache/lplib')

    for directory in os.listdir(os.getcwd()):
        if os.path.isdir(directory):
            try:
                bzr_info = check_output(['bzr','info', directory],
                                        universal_newlines=True)
            except CalledProcessError:
                print("{} is not a bzr branch.".format(directory))
            push_branch = PUSH_RE.search(bzr_info)
            if push_branch:
                branch = lp.branches.getByUrl(url=push_branch.group())
                if (branch and branch.lifecycle_status == 'Merged' or
                    _was_merged(branch)):
                    print("{} was merged, deleting {}".format(branch.web_link,
                                                              directory))
                    shutil.rmtree(directory)

if __name__ == "__main__":
    sys.exit(main())
