#!/usr/bin/python

import os
import sys

from launchpadlib.launchpad import Launchpad
from argparse import ArgumentParser
from subprocess import check_call
from tempfile import NamedTemporaryFile


def main():
    parser = ArgumentParser("A script for filing new bugs in Launchpad.")
    parser.add_argument("title",
                        help="Bug title")
    parser.add_argument("--project",
                        help="""Project to file the bug against - defaults
                                to Ubuntu itself.""",
                        default="ubuntu")
    parser.add_argument("--package",
                        help="Package to file the bug against, if appropriate")
    parser.add_argument("--description","-d",
                        help="""Brief description of the bug, if desired.
                                It is recommended to use the inbuilt editor
                                to write a more verbose description though.""")
    parser.add_argument("--tag","-t",
                        help="Bug tag - can only specify one due to LP limit")
    parser.add_argument("--private",
                        action="store_true",
                        default=False,
                        help="Whether the bug should be created as private.")
    args = parser.parse_args()

    try:
        lp = Launchpad.login_with(sys.argv[0], 'production')
    except:
        print("Unable to access Launchpad service.")
        return 1

    # Get the description from 'your favourite editor'
    description = args.description
    if not description:
        editor = os.environ.get('EDITOR','nano').split()
        tempfile = NamedTemporaryFile(delete=False)
        editor.append(tempfile.name)
        try:
            check_call(editor)
        except OSError:
            print("Failed to open preferred editor '%s'" % editor)
        description = tempfile.read()

    # Work out the target from project and package specified
    target = None
    if args.project:
        target = lp.projects[args.project].self_link
    if args.package:
        target += '/+source/' + args.package
    kwargs = {'target': target,
              'title': args.title,
              'description': description}
    if args.private:
        kwargs['private'] = args.private
    if args.tag:
        kwargs['tags'] = args.tag
    try:
        bug = lp.bugs.createBug(**kwargs)
        print(bug.web_link)
    except:
        print("Unable to file bug in:")
        print("\tproject: %s" % args.project)

        if args.package:
            print("\tpackage: %s" % args.package)

        print("Please check that the project and/or package name are correct.")

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