#!/usr/bin/python

from arsenal.arsenal_lib import *
from lpltk import LaunchpadService

lp          = LaunchpadService()
d           = lp.launchpad.distributions["ubuntu"]

# Retrieve all bugs subscriber is subscribed to

def unsub(person, bugnr):
    bug = lp.get_bug(sys.argv[1])

    print bug.id, "  ", bug.title
    for s in bug.subscriptions:
        if s.person.name in subscribers:
            try:
                # TODO:  launchpadlib's API doesn't permit a person argument (LP: #321738)
                bug.unsubscribe(s.person)
                print "Unsubscribed ",s.person.name
            except:
                print >> sys.stderr, "Failed to unsubscribe ",s.person.name
                raise

def main():
    if len(sys.argv) < 3:
        print >> sys.stderr, "Usage: unsub <email> <package> [package [...]]"
        sys.exit(1)

    # TODO:  Parameterize
    subscriber  = sys.argv[1]
    persons = lp.launchpad.people.find(text = subscriber)

    #if len(persons) > 1:
    #    sys.stderr.write("Error:  More than one match to %s\n" % subscriber)
    #    sys.exit(1)
    person = persons[0]

    for pkg in sys.argv[2:]:
        print pkg
        s = d.getSourcePackage(name = pkg)

        for bugtask in s.searchTasks(bug_subscriber = person):
            bug = ArsenalBug(bugtask.bug, lp.launchpad)
            title = bug.title.decode("utf-8")
            print "%-7s %-11s %s" % (bug.id, bugtask.status, title)
            bug.bug.unsubscribe(person = person)

if __name__ == '__main__':
        main()
