#!/usr/bin/python
import email.header
import email.parser
import re
import subprocess
import sys
import shlex
from l3tlib import CommandError
from l3tlib.command import L3tCommand


class Action(L3tCommand):

    usage = "%prog <l3t command>"
    descr = """\
Runs an l3t command with the bug number extracted from a Bugzilla
or Solid Ground notification message.
"""

    def init_parser(self, parser):
        super(Action, self).init_parser(parser)
        parser.add_option("--ask", default=False, action="store_true",
                          help="ask for a command to be run")
        parser.add_option("--file", default=None,
                          help="load the bug from a file")

    def parse_args(self, parser, values):
        opts, args = super(Action, self).parse_args(parser, values)
        if not (args or opts.ask):
            parser.error("--ask or command missing")
        return opts, args

    def extract(self, message):
        incident = message["X-SG-Incident-Id"]
        found = None
        for (decoded, _) in email.header.decode_header(message["Subject"]):
            found = re.search("\[Bug (?P<bug_id>[^\]]+)\]", decoded)
            if found:
                break
        bug_id = found.group("bug_id") if found else None
        return incident, bug_id

    def run(self):
        if self.opts.file:
            source = open(self.opts.file)
        else:
            source = sys.stdin
        message = email.parser.Parser().parse(source)
        incident, bug_id = self.extract(message)
        if incident:
            append = ["-i", incident]
        elif bug_id:
            append = ["-b", bug_id]
        else:
            raise CommandError("no bug or incident found in message")
        if self.opts.ask:
            try:
                cmdline = shlex.split(raw_input("> "))
            except EOFError:
                sys.exit(0)
            if not cmdline:
                sys.exit(0)
        else:
            cmdline = self.args[:]
        cmdline.extend(append)
        try:
            sys.exit(subprocess.call(cmdline, shell=False))
        except EnvironmentError, e:
            raise CommandError("failed to run: %s" % (e))


Action().main()
