#!/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="The bug title used to describe it.")
    parser.add_argument("--project","-p",
                        help="The project to file the bug against.",
                        default="ubuntu")
    parser.add_argument("--package","-P",
                        help="The package to file the bug against.")
    args = parser.parse_args()

    lp = LaunchpadService()

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