#!/usr/bin/python

import os
import sys

from argparse import ArgumentParser
from lpltk import LaunchpadService
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","-p",
                        help="""Project to file the bug against - defaults
                                to Ubuntu itself.""",
                        default="ubuntu")
    parser.add_argument("--package","-P",
                        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",
                        nargs='+',
                        help="Bug tags - specify as many as needed")
    args = parser.parse_args()

    try:
        lp = LaunchpadService()
    except:
        print("Unable to access Launchpad service.")
        return 1

    # TODO: Get the description for '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()

    try:
        bug = lp.create_bug(args.project, args.package,
                            title=args.title,
                            description=description,
                            tags=args.tag)
        print(bug.lpbug.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())
