#!/usr/bin/python3 -s
import shlex
import subprocess
from l3tlib import CommandError
from l3tlib.command import L3tCommand

import six


CONF_SECTION = "product-map"
PLATFORM_MAP = {"x86-64": "x86_64"}


class PtfCreate(L3tCommand):

    usage = ("%prog PACKAGE [-- PTFSETUP OPTIONS]")
    descr = """\
Wrapper around ptfsetup

It doesn't require specifying the incident number or bug when using the CWB
(see README.md).
"""

    def init_parser(self, parser):
        super(PtfCreate, self).init_parser(parser)
        parser.add_option("-i", "--incident", type="int",
                          help="incident number")
        parser.add_option("-b", "--bug", type="int",
                          help="bug number")
        parser.add_option("-D", "--product", default=None,
                          help="Set the product name")
        parser.add_option("-a", "--arch", default=None,
                          help="Set the architecture")
        parser.add_option("-r", "--revision", default=None,
                          help="-r for ptfsetup")

    def parse_args(self, parser, args):
        opts, values = super(PtfCreate, self).parse_args(parser, args)
        if len(values) != 1:
            parser.error("the package name is needed")
        return opts, values

    def product_map(self):
        raw_map = dict(self.config.get_section(CONF_SECTION).get_items())
        map = dict((bz_name, ptfdb_name)
                   for bz_name, ptfdb_name in raw_map.items())
        return map

    def run(self):
        product_map = self.product_map()
        incident = self.l3t.get_incident(self.opts.incident, self.opts.bug,
                                         running=True)
        product_name = self.opts.product
        if not product_name:
            try:
                product_name = product_map[incident.bug.product]
            except KeyError:
                raise CommandError("entry for %s missing in the section [%s] "
                                   "of the configuration" %
                                   (incident.bug.product, CONF_SECTION))
        product_arch = self.opts.arch
        if not product_arch:
            product_arch = PLATFORM_MAP.get(incident.bug.platform,
                                            product_arch or "x86_64")
        ptfsetup_product = product_name + "-" + product_arch
        cmdline = shlex.split(self.config.ptfutils.ptfsetup_command)
        cmdline.extend(("-D", ptfsetup_product))
        if self.opts.revision:
            cmdline.extend(("-r", self.opts.revision))
        cmdline.append(self.args[0])
        cmdline.extend(self.args[1:])
        cmdline.append("L3:%s" % (incident.id))
        six.print_("Running", cmdline)
        subprocess.call(cmdline)


PtfCreate().main()
