#!/usr/bin/env python

import re
import sys
from lpltk import LaunchpadService

if len(sys.argv) < 4:
    print "Usage:  search-attachments <source-package> <attachment-name-regex> <search-regex>"
    sys.exit(2)

source_pkg   = sys.argv[1]
attach_regex = sys.argv[2]
text_regex   = ' '.join(sys.argv[3:])
lp           = LaunchpadService(config={'read_only':True})
d            = lp.distributions["ubuntu"]
re_text      = re.compile(text_regex)
re_filename  = re.compile(attach_regex)

s = d.get_source_package(source_pkg)
# TODO: Search by given tag (current devel release)
for bug_task in s.search_tasks(tags="precise",
                               tags_combinator="All",
                               omit_duplicates=False):
    bug = bug_task.bug
    found_attachments = []
    for a in bug.attachments:
        if not re_filename.search(a.title):
            continue

        hosted_file = a.data
        hosted_file_buffer = hosted_file.open()
        content = hosted_file_buffer.read()

        if re_text.search(content):
            found_attachments.append(a)

    if len(found_attachments)>0:
        print "%d: %s %s" %(bug.id, bug_task.status, bug.title)
        dupe = bug.duplicate_of
        if dupe:
            print "  + Dupe of %d: %s" %(dupe.id, dupe.title)

