#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Canonical Ltd.
#
# Modified by Iain Lane <iain@orangesquash.org.uk>, taking some code written by
# Daniel Hahler <ubuntu@thequod.de>
#
# ##################################################################
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 3.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# See file /usr/share/common-licenses/GPL-3 for more details.
#
# ##################################################################

import os
import sys
import email
import subprocess
import glob

import launchpadbugs.connector as Connector

sys.path.append('/usr/share/ubuntu-dev-tools/')
import common

cookie = common.prepareLaunchpadCookie()

def read_config():
    instructions_file = open("instructions")
    instructions = email.message_from_file(instructions_file)
    instructions_file.close()
    instr = dict()
    
    for field in "subject", "assignee", "subscribers", "tags", "text", \
                 "buglist-url", "status":
        instr[field] = instructions.get(field)
    
    return instr

def read_list():
    pack_list = set()

    listfile = open("list")
    for line in listfile.readlines():
        if line.strip()!="":
            pack_list.add(line.strip("\n"))

    listfile.close()
    return pack_list

def file_bug():
    Bug = Connector.ConnectBug()
    Bug.authentication = cookie

def check_configfiles():
    result = True

    bin_path = os.path.dirname(os.path.abspath(__file__))
    if bin_path == "/usr/bin":
        example_dir = "/usr/share/doc/ubuntu-dev-tools/examples"
    else:
        example_dir = "%s/examples" % bin_path

    if not os.path.exists("instructions"):
        os.system("cp %s/massfile.instructions instructions" % example_dir)
        print >> sys.stderr, \
            "No 'instructions' file found. Copied template from %s." % \
            example_dir
        result = False

    if not os.path.exists("list"):
        os.system("cp %s/massfile.list list" % example_dir)
        print >> sys.stderr, \
            "No 'list' file found. Copied template from %s." % example_dir
        result = False

    return result


def file_bug(config):
    Bug = Connector.ConnectBug()

    Bug.authentication = cookie

    try:
        summary = config["subject"].replace("$pack", config["sourcepackage"])
        description = config["text"].replace("$pack", config["sourcepackage"])
        
        bug = Bug.New(product={"name": config["sourcepackage"], 
                               "target": "ubuntu"},
                      summary=summary,
                      description=description)
        print "Successfully filed bug %s: http://launchpad.net/bugs/%s" % \
            (bug.bugnumber, bug.bugnumber)
        for sub in config["subscribers"].split(","):
            if sub.strip("\n").strip():
                bug.subscribers.add(sub.strip("\n").strip())
        for tag in config["tags"].split(","):
            if tag.strip("\n").strip():
                bug.tags.append(tag.strip("\n").strip())
        bug.assignee = config["assignee"]
        if config["status"]:
            bug.status = config["status"].capitalize()
        else:
            bug.status = "Confirmed"
        bug.commit()
    except:
        "Bug for '%s' was not filed." % config["sourcepackage"]

def read_buglist(url):
    BugList = Connector.ConnectBugList()
    packages = set()

    if url:
        buglist = BugList(url)
        for bug in buglist.bugs:
            packages.add(bug.sourcepackage)
        
    return packages

def main():
    if not check_configfiles():
        sys.exit(1)

    config = read_config()
    pack_list = read_list()
    buglist = read_buglist(config["buglist-url"])
	
    for pack in pack_list:
        if pack not in buglist:
            config["sourcepackage"] = pack
            file_bug(config)

	
if __name__ == '__main__':
    main()