"""Let's Encrypt CLI."""
# TODO: Sanity check all input.  Be sure to avoid shell code etc...
# pylint: disable=too-many-lines
# (TODO: split this file into main.py and cli.py)
import argparse
import atexit
import functools
import json
import logging
import logging.handlers
import os
import sys
import time
import traceback

import configargparse
import OpenSSL
import zope.component
import zope.interface.exceptions
import zope.interface.verify

from acme import jose

import letsencrypt

from letsencrypt import account
from letsencrypt import colored_logging
from letsencrypt import configuration
from letsencrypt import constants
from letsencrypt import client
from letsencrypt import crypto_util
from letsencrypt import errors
from letsencrypt import interfaces
from letsencrypt import le_util
from letsencrypt import log
from letsencrypt import reporter
from letsencrypt import storage

from letsencrypt.display import util as display_util
from letsencrypt.display import ops as display_ops
from letsencrypt.plugins import disco as plugins_disco

logger = logging.getLogger(__name__)


# Argparse's help formatting has a lot of unhelpful peculiarities, so we want
# to replace as much of it as we can...

# This is the stub to include in help generated by argparse

SHORT_USAGE = """
  letsencrypt [SUBCOMMAND] [options] [-d domain] [-d domain] ...

The Let's Encrypt agent can obtain and install HTTPS/TLS/SSL certificates.  By
default, it will attempt to use a webserver both for obtaining and installing
the cert. Major SUBCOMMANDS are:

  (default) run        Obtain & install a cert in your current webserver
  certonly             Obtain cert, but do not install it (aka "auth")
  install              Install a previously obtained cert in a server
  revoke               Revoke a previously obtained certificate
  rollback             Rollback server configuration changes made during install
  config_changes       Show changes made to server config during installation
  plugins              Display information about installed plugins

"""

# This is the short help for letsencrypt --help, where we disable argparse
# altogether
USAGE = SHORT_USAGE + """Choice of server plugins for obtaining and installing cert:

  %s
  --standalone      Run a standalone webserver for authentication
  %s
  --webroot         Place files in a server's webroot folder for authentication

OR use different plugins to obtain (authenticate) the cert and then install it:

  --authenticator standalone --installer apache

More detailed help:

  -h, --help [topic]    print this message, or detailed help on a topic;
                        the available topics are:

   all, automation, paths, security, testing, or any of the subcommands or
   plugins (certonly, install, nginx, apache, standalone, webroot, etc)
"""


def usage_strings(plugins):
    """Make usage strings late so that plugins can be initialised late"""
    if "nginx" in plugins:
        nginx_doc = "--nginx           Use the Nginx plugin for authentication & installation"
    else:
        nginx_doc = "(nginx support is experimental, buggy, and not installed by default)"
    if "apache" in plugins:
        apache_doc = "--apache          Use the Apache plugin for authentication & installation"
    else:
        apache_doc = "(the apache plugin is not installed)"
    return USAGE % (apache_doc, nginx_doc), SHORT_USAGE


def _find_domains(args, installer):
    if not args.domains:
        domains = display_ops.choose_names(installer)
    else:
        domains = args.domains

    if not domains:
        raise errors.Error("Please specify --domains, or --installer that "
                           "will help in domain names autodiscovery")

    return domains


def _determine_account(args, config):
    """Determine which account to use.

    In order to make the renewer (configuration de/serialization) happy,
    if ``args.account`` is ``None``, it will be updated based on the
    user input. Same for ``args.email``.

    :param argparse.Namespace args: CLI arguments
    :param letsencrypt.interface.IConfig config: Configuration object
    :param .AccountStorage account_storage: Account storage.

    :returns: Account and optionally ACME client API (biproduct of new
        registration).
    :rtype: `tuple` of `letsencrypt.account.Account` and
        `acme.client.Client`

    """
    account_storage = account.AccountFileStorage(config)
    acme = None

    if args.account is not None:
        acc = account_storage.load(args.account)
    else:
        accounts = account_storage.find_all()
        if len(accounts) > 1:
            acc = display_ops.choose_account(accounts)
        elif len(accounts) == 1:
            acc = accounts[0]
        else:  # no account registered yet
            if args.email is None and not args.register_unsafely_without_email:
                args.email = display_ops.get_email()

            def _tos_cb(regr):
                if args.tos:
                    return True
                msg = ("Please read the Terms of Service at {0}. You "
                       "must agree in order to register with the ACME "
                       "server at {1}".format(
                           regr.terms_of_service, config.server))
                return zope.component.getUtility(interfaces.IDisplay).yesno(
                    msg, "Agree", "Cancel")

            try:
                acc, acme = client.register(
                    config, account_storage, tos_cb=_tos_cb)
            except errors.Error as error:
                logger.debug(error, exc_info=True)
                raise errors.Error(
                    "Unable to register an account with ACME server")

    args.account = acc.id
    return acc, acme


def _init_le_client(args, config, authenticator, installer):
    if authenticator is not None:
        # if authenticator was given, then we will need account...
        acc, acme = _determine_account(args, config)
        logger.debug("Picked account: %r", acc)
        # XXX
        #crypto_util.validate_key_csr(acc.key)
    else:
        acc, acme = None, None

    return client.Client(config, acc, authenticator, installer, acme=acme)


def _find_duplicative_certs(config, domains):
    """Find existing certs that duplicate the request."""

    identical_names_cert, subset_names_cert = None, None

    cli_config = configuration.RenewerConfiguration(config)
    configs_dir = cli_config.renewal_configs_dir
    # Verify the directory is there
    le_util.make_or_verify_dir(configs_dir, mode=0o755, uid=os.geteuid())

    for renewal_file in os.listdir(configs_dir):
        try:
            full_path = os.path.join(configs_dir, renewal_file)
            candidate_lineage = storage.RenewableCert(full_path, cli_config)
        except (errors.CertStorageError, IOError):
            logger.warning("Renewal configuration file %s is broken. "
                           "Skipping.", full_path)
            continue
        # TODO: Handle these differently depending on whether they are
        #       expired or still valid?
        candidate_names = set(candidate_lineage.names())
        if candidate_names == set(domains):
            identical_names_cert = candidate_lineage
        elif candidate_names.issubset(set(domains)):
            subset_names_cert = candidate_lineage

    return identical_names_cert, subset_names_cert


def _treat_as_renewal(config, domains):
    """Determine whether or not the call should be treated as a renewal.

    :returns: RenewableCert or None if renewal shouldn't occur.
    :rtype: :class:`.storage.RenewableCert`

    :raises .Error: If the user would like to rerun the client again.

    """
    renewal = False

    # Considering the possibility that the requested certificate is
    # related to an existing certificate.  (config.duplicate, which
    # is set with --duplicate, skips all of this logic and forces any
    # kind of certificate to be obtained with renewal = False.)
    if not config.duplicate:
        ident_names_cert, subset_names_cert = _find_duplicative_certs(
            config, domains)
        # I am not sure whether that correctly reads the systemwide
        # configuration file.
        question = None
        if ident_names_cert is not None:
            question = (
                "You have an existing certificate that contains exactly the "
                "same domains you requested (ref: {0}){br}{br}Do you want to "
                "renew and replace this certificate with a newly-issued one?"
            ).format(ident_names_cert.configfile.filename, br=os.linesep)
        elif subset_names_cert is not None:
            question = (
                "You have an existing certificate that contains a portion of "
                "the domains you requested (ref: {0}){br}{br}It contains these "
                "names: {1}{br}{br}You requested these names for the new "
                "certificate: {2}.{br}{br}Do you want to replace this existing "
                "certificate with the new certificate?"
            ).format(subset_names_cert.configfile.filename,
                     ", ".join(subset_names_cert.names()),
                     ", ".join(domains),
                     br=os.linesep)
        if question is None:
            # We aren't in a duplicative-names situation at all, so we don't
            # have to tell or ask the user anything about this.
            pass
        elif config.renew_by_default or zope.component.getUtility(
                interfaces.IDisplay).yesno(question, "Replace", "Cancel"):
            renewal = True
        else:
            reporter_util = zope.component.getUtility(interfaces.IReporter)
            reporter_util.add_message(
                "To obtain a new certificate that {0} an existing certificate "
                "in its domain-name coverage, you must use the --duplicate "
                "option.{br}{br}For example:{br}{br}{1} --duplicate {2}".format(
                    "duplicates" if ident_names_cert is not None else
                    "overlaps with",
                    sys.argv[0], " ".join(sys.argv[1:]),
                    br=os.linesep
                ),
                reporter_util.HIGH_PRIORITY)
            raise errors.Error(
                "User did not use proper CLI and would like "
                "to reinvoke the client.")

        if renewal:
            return ident_names_cert if ident_names_cert is not None else subset_names_cert

    return None


def _report_new_cert(cert_path, fullchain_path):
    """Reports the creation of a new certificate to the user.

    :param str cert_path: path to cert
    :param str fullchain_path: path to full chain

    """
    expiry = crypto_util.notAfter(cert_path).date()
    reporter_util = zope.component.getUtility(interfaces.IReporter)
    if fullchain_path:
        # Print the path to fullchain.pem because that's what modern webservers
        # (Nginx and Apache2.4) will want.
        and_chain = "and chain have"
        path = fullchain_path
    else:
        # Unless we're in .csr mode and there really isn't one
        and_chain = "has "
        path = cert_path
    # XXX Perhaps one day we could detect the presence of known old webservers
    # and say something more informative here.
    msg = ("Congratulations! Your certificate {0} been saved at {1}."
           " Your cert will expire on {2}. To obtain a new version of the "
           "certificate in the future, simply run Let's Encrypt again."
           .format(and_chain, path, expiry))
    reporter_util.add_message(msg, reporter_util.MEDIUM_PRIORITY)

def _suggest_donate():
    "Suggest a donation to support Let's Encrypt"
    reporter_util = zope.component.getUtility(interfaces.IReporter)
    msg = ("If like Let's Encrypt, please consider supporting our work by:\n\n"
           "Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate\n"
           "Donating to EFF:                    https://eff.org/donate-le\n\n")
    reporter_util.add_message(msg, reporter_util.LOW_PRIORITY)


def _auth_from_domains(le_client, config, domains):
    """Authenticate and enroll certificate."""
    # Note: This can raise errors... caught above us though.
    lineage = _treat_as_renewal(config, domains)

    if lineage is not None:
        # TODO: schoen wishes to reuse key - discussion
        # https://github.com/letsencrypt/letsencrypt/pull/777/files#r40498574
        new_certr, new_chain, new_key, _ = le_client.obtain_certificate(domains)
        # TODO: Check whether it worked! <- or make sure errors are thrown (jdk)
        lineage.save_successor(
            lineage.latest_common_version(), OpenSSL.crypto.dump_certificate(
                OpenSSL.crypto.FILETYPE_PEM, new_certr.body),
            new_key.pem, crypto_util.dump_pyopenssl_chain(new_chain))

        lineage.update_all_links_to(lineage.latest_common_version())
        # TODO: Check return value of save_successor
        # TODO: Also update lineage renewal config with any relevant
        #       configuration values from this attempt? <- Absolutely (jdkasten)
    else:
        # TREAT AS NEW REQUEST
        lineage = le_client.obtain_and_enroll_certificate(domains)
        if not lineage:
            raise errors.Error("Certificate could not be obtained")

    _report_new_cert(lineage.cert, lineage.fullchain)

    return lineage


def set_configurator(previously, now):
    """
    Setting configurators multiple ways is okay, as long as they all agree
    :param str previously: previously identified request for the installer/authenticator
    :param str requested: the request currently being processed
    """
    if now is None:
        # we're not actually setting anything
        return previously
    if previously:
        if previously != now:
            msg = "Too many flags setting configurators/installers/authenticators {0} -> {1}"
            raise errors.PluginSelectionError(msg.format(repr(previously), repr(now)))
    return now


def diagnose_configurator_problem(cfg_type, requested, plugins):
    """
    Raise the most helpful error message about a plugin being unavailable

    :param str cfg_type: either "installer" or "authenticator"
    :param str requested: the plugin that was requested
    :param .PluginsRegistry plugins: available plugins

    :raises error.PluginSelectionError: if there was a problem
    """

    if requested:
        if requested not in plugins:
            msg = "The requested {0} plugin does not appear to be installed".format(requested)
        else:
            msg = ("The {0} plugin is not working; there may be problems with "
                   "your existing configuration.\nThe error was: {1!r}"
                   .format(requested, plugins[requested].problem))
    elif cfg_type == "installer":
        if os.path.exists("/etc/debian_version"):
            # Debian... installers are at least possible
            msg = ('No installers seem to be present and working on your system; '
                   'fix that or try running letsencrypt with the "certonly" command')
        else:
            # XXX update this logic as we make progress on #788 and nginx support
            msg = ('No installers are available on your OS yet; try running '
                   '"letsencrypt-auto certonly" to get a cert you can install manually')
    else:
        msg = "{0} could not be determined or is not installed".format(cfg_type)
    raise errors.PluginSelectionError(msg)


def choose_configurator_plugins(args, config, plugins, verb):  # pylint: disable=too-many-branches
    """
    Figure out which configurator we're going to use
    :raises error.PluginSelectionError if there was a problem
    """

    # Which plugins do we need?
    need_inst = need_auth = (verb == "run")
    if verb == "certonly":
        need_auth = True
    if verb == "install":
        need_inst = True
        if args.authenticator:
            logger.warn("Specifying an authenticator doesn't make sense in install mode")

    # Which plugins did the user request?
    req_inst = req_auth = args.configurator
    req_inst = set_configurator(req_inst, args.installer)
    req_auth = set_configurator(req_auth, args.authenticator)
    if args.nginx:
        req_inst = set_configurator(req_inst, "nginx")
        req_auth = set_configurator(req_auth, "nginx")
    if args.apache:
        req_inst = set_configurator(req_inst, "apache")
        req_auth = set_configurator(req_auth, "apache")
    if args.standalone:
        req_auth = set_configurator(req_auth, "standalone")
    if args.webroot:
        req_auth = set_configurator(req_auth, "webroot")
    if args.manual:
        req_auth = set_configurator(req_auth, "manual")
    logger.debug("Requested authenticator %s and installer %s", req_auth, req_inst)

    # Try to meet the user's request and/or ask them to pick plugins
    authenticator = installer = None
    if verb == "run" and req_auth == req_inst:
        # Unless the user has explicitly asked for different auth/install,
        # only consider offering a single choice
        authenticator = installer = display_ops.pick_configurator(config, req_inst, plugins)
    else:
        if need_inst or req_inst:
            installer = display_ops.pick_installer(config, req_inst, plugins)
        if need_auth:
            authenticator = display_ops.pick_authenticator(config, req_auth, plugins)
    logger.debug("Selected authenticator %s and installer %s", authenticator, installer)

    # Report on any failures
    if need_inst and not installer:
        diagnose_configurator_problem("installer", req_inst, plugins)
    if need_auth and not authenticator:
        diagnose_configurator_problem("authenticator", req_auth, plugins)

    record_chosen_plugins(config, plugins, authenticator, installer)
    return installer, authenticator


def record_chosen_plugins(config, plugins, auth, inst):
    "Update the config entries to reflect the plugins we actually selected."
    cn = config.namespace
    cn.authenticator = plugins.find_init(auth).name if auth else "none"
    cn.installer = plugins.find_init(inst).name if inst else "none"


# TODO: Make run as close to auth + install as possible
# Possible difficulties: args.csr was hacked into auth
def run(args, config, plugins):  # pylint: disable=too-many-branches,too-many-locals
    """Obtain a certificate and install."""
    try:
        installer, authenticator = choose_configurator_plugins(args, config, plugins, "run")
    except errors.PluginSelectionError, e:
        return e.message

    domains = _find_domains(args, installer)

    # TODO: Handle errors from _init_le_client?
    le_client = _init_le_client(args, config, authenticator, installer)

    lineage = _auth_from_domains(le_client, config, domains)

    le_client.deploy_certificate(
        domains, lineage.privkey, lineage.cert,
        lineage.chain, lineage.fullchain)

    le_client.enhance_config(domains, config)

    if len(lineage.available_versions("cert")) == 1:
        display_ops.success_installation(domains)
    else:
        display_ops.success_renewal(domains)

    _suggest_donate()


def obtain_cert(args, config, plugins):
    """Authenticate & obtain cert, but do not install it."""

    if args.domains and args.csr is not None:
        # TODO: --csr could have a priority, when --domains is
        # supplied, check if CSR matches given domains?
        return "--domains and --csr are mutually exclusive"

    try:
        # installers are used in auth mode to determine domain names
        installer, authenticator = choose_configurator_plugins(args, config, plugins, "certonly")
    except errors.PluginSelectionError, e:
        return e.message

    # TODO: Handle errors from _init_le_client?
    le_client = _init_le_client(args, config, authenticator, installer)

    # This is a special case; cert and chain are simply saved
    if args.csr is not None:
        certr, chain = le_client.obtain_certificate_from_csr(le_util.CSR(
            file=args.csr[0], data=args.csr[1], form="der"))
        cert_path, _, cert_fullchain = le_client.save_certificate(
            certr, chain, args.cert_path, args.chain_path, args.fullchain_path)
        _report_new_cert(cert_path, cert_fullchain)
    else:
        domains = _find_domains(args, installer)
        _auth_from_domains(le_client, config, domains)

    _suggest_donate()


def install(args, config, plugins):
    """Install a previously obtained cert in a server."""
    # XXX: Update for renewer/RenewableCert

    try:
        installer, _ = choose_configurator_plugins(args, config,
                                                   plugins, "install")
    except errors.PluginSelectionError, e:
        return e.message

    domains = _find_domains(args, installer)
    le_client = _init_le_client(
        args, config, authenticator=None, installer=installer)
    assert args.cert_path is not None  # required=True in the subparser
    le_client.deploy_certificate(
        domains, args.key_path, args.cert_path, args.chain_path,
        args.fullchain_path)
    le_client.enhance_config(domains, config)


def revoke(args, config, unused_plugins):  # TODO: coop with renewal config
    """Revoke a previously obtained certificate."""
    # For user-agent construction
    config.namespace.installer = config.namespace.authenticator = "none"
    if args.key_path is not None:  # revocation by cert key
        logger.debug("Revoking %s using cert key %s",
                     args.cert_path[0], args.key_path[0])
        key = jose.JWK.load(args.key_path[1])
    else:  # revocation by account key
        logger.debug("Revoking %s using Account Key", args.cert_path[0])
        acc, _ = _determine_account(args, config)
        key = acc.key
    acme = client.acme_from_config_key(config, key)
    cert = crypto_util.pyopenssl_load_certificate(args.cert_path[1])[0]
    acme.revoke(jose.ComparableX509(cert))


def rollback(args, config, plugins):
    """Rollback server configuration changes made during install."""
    client.rollback(args.installer, args.checkpoints, config, plugins)


def config_changes(unused_args, config, unused_plugins):
    """Show changes made to server config during installation

    View checkpoints and associated configuration changes.

    """
    client.view_config_changes(config)


def plugins_cmd(args, config, plugins):  # TODO: Use IDisplay rather than print
    """List server software plugins."""
    logger.debug("Expected interfaces: %s", args.ifaces)

    ifaces = [] if args.ifaces is None else args.ifaces
    filtered = plugins.visible().ifaces(ifaces)
    logger.debug("Filtered plugins: %r", filtered)

    if not args.init and not args.prepare:
        print str(filtered)
        return

    filtered.init(config)
    verified = filtered.verify(ifaces)
    logger.debug("Verified plugins: %r", verified)

    if not args.prepare:
        print str(verified)
        return

    verified.prepare()
    available = verified.available()
    logger.debug("Prepared plugins: %s", available)
    print str(available)


def read_file(filename, mode="rb"):
    """Returns the given file's contents.

    :param str filename: path to file
    :param str mode: open mode (see `open`)

    :returns: absolute path of filename and its contents
    :rtype: tuple

    :raises argparse.ArgumentTypeError: File does not exist or is not readable.

    """
    try:
        filename = os.path.abspath(filename)
        return filename, open(filename, mode).read()
    except IOError as exc:
        raise argparse.ArgumentTypeError(exc.strerror)


def flag_default(name):
    """Default value for CLI flag."""
    return constants.CLI_DEFAULTS[name]


def config_help(name, hidden=False):
    """Help message for `.IConfig` attribute."""
    if hidden:
        return argparse.SUPPRESS
    else:
        return interfaces.IConfig[name].__doc__


class SilentParser(object):  # pylint: disable=too-few-public-methods
    """Silent wrapper around argparse.

    A mini parser wrapper that doesn't print help for its
    arguments. This is needed for the use of callbacks to define
    arguments within plugins.

    """
    def __init__(self, parser):
        self.parser = parser

    def add_argument(self, *args, **kwargs):
        """Wrap, but silence help"""
        kwargs["help"] = argparse.SUPPRESS
        self.parser.add_argument(*args, **kwargs)


class HelpfulArgumentParser(object):
    """Argparse Wrapper.

    This class wraps argparse, adding the ability to make --help less
    verbose, and request help on specific subcategories at a time, eg
    'letsencrypt --help security' for security options.

    """

    # Maps verbs/subcommands to the functions that implement them
    VERBS = {"auth": obtain_cert, "certonly": obtain_cert,
             "config_changes": config_changes, "everything": run,
             "install": install, "plugins": plugins_cmd,
             "revoke": revoke, "rollback": rollback, "run": run}

    # List of topics for which additional help can be provided
    HELP_TOPICS = ["all", "security",
                   "paths", "automation", "testing"] + VERBS.keys()

    def __init__(self, args, plugins):
        plugin_names = [name for name, _p in plugins.iteritems()]
        self.help_topics = self.HELP_TOPICS + plugin_names + [None]
        usage, short_usage = usage_strings(plugins)
        self.parser = configargparse.ArgParser(
            usage=short_usage,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            args_for_setting_config_path=["-c", "--config"],
            default_config_files=flag_default("config_files"))

        # This is the only way to turn off overly verbose config flag documentation
        self.parser._add_config_file_help = False  # pylint: disable=protected-access
        self.silent_parser = SilentParser(self.parser)

        self.args = args
        self.determine_verb()
        help1 = self.prescan_for_flag("-h", self.help_topics)
        help2 = self.prescan_for_flag("--help", self.help_topics)
        assert max(True, "a") == "a", "Gravity changed direction"
        self.help_arg = max(help1, help2)
        if self.help_arg is True:
            # just --help with no topic; avoid argparse altogether
            print usage
            sys.exit(0)
        self.visible_topics = self.determine_help_topics(self.help_arg)
        self.groups = {}  # elements are added by .add_group()

    def parse_args(self):
        """Parses command line arguments and returns the result.

        :returns: parsed command line arguments
        :rtype: argparse.Namespace

        """
        parsed_args = self.parser.parse_args(self.args)
        parsed_args.func = self.VERBS[self.verb]

        return parsed_args


    def determine_verb(self):
        """Determines the verb/subcommand provided by the user.

        This function works around some of the limitations of argparse.

        """
        if "-h" in self.args or "--help" in self.args:
            # all verbs double as help arguments; don't get them confused
            self.verb = "help"
            return

        for i, token in enumerate(self.args):
            if token in self.VERBS:
                verb = token
                if verb == "auth":
                    verb = "certonly"
                if verb == "everything":
                    verb = "run"
                self.verb = verb
                self.args.pop(i)
                return

        self.verb = "run"

    def prescan_for_flag(self, flag, possible_arguments):
        """Checks cli input for flags.

        Check for a flag, which accepts a fixed set of possible arguments, in
        the command line; we will use this information to configure argparse's
        help correctly.  Return the flag's argument, if it has one that matches
        the sequence @possible_arguments; otherwise return whether the flag is
        present.

        """
        if flag not in self.args:
            return False
        pos = self.args.index(flag)
        try:
            nxt = self.args[pos + 1]
            if nxt in possible_arguments:
                return nxt
        except IndexError:
            pass
        return True

    def add(self, topic, *args, **kwargs):
        """Add a new command line argument.

        @topic is required, to indicate which part of the help will document
        it, but can be None for `always documented'.

        """
        if self.visible_topics[topic]:
            if topic in self.groups:
                group = self.groups[topic]
                group.add_argument(*args, **kwargs)
            else:
                self.parser.add_argument(*args, **kwargs)
        else:
            kwargs["help"] = argparse.SUPPRESS
            self.parser.add_argument(*args, **kwargs)

    def add_deprecated_argument(self, argument_name, num_args):
        """Adds a deprecated argument with the name argument_name.

        Deprecated arguments are not shown in the help. If they are used
        on the command line, a warning is shown stating that the
        argument is deprecated and no other action is taken.

        :param str argument_name: Name of deprecated argument.
        :param int nargs: Number of arguments the option takes.

        """
        le_util.add_deprecated_argument(
            self.parser.add_argument, argument_name, num_args)

    def add_group(self, topic, **kwargs):
        """

        This has to be called once for every topic; but we leave those calls
        next to the argument definitions for clarity. Return something
        arguments can be added to if necessary, either the parser or an argument
        group.

        """
        if self.visible_topics[topic]:
            #print "Adding visible group " + topic
            group = self.parser.add_argument_group(topic, **kwargs)
            self.groups[topic] = group
            return group
        else:
            #print "Invisible group " + topic
            return self.silent_parser

    def add_plugin_args(self, plugins):
        """

        Let each of the plugins add its own command line arguments, which
        may or may not be displayed as help topics.

        """
        for name, plugin_ep in plugins.iteritems():
            parser_or_group = self.add_group(name, description=plugin_ep.description)
            #print parser_or_group
            plugin_ep.plugin_cls.inject_parser_options(parser_or_group, name)

    def determine_help_topics(self, chosen_topic):
        """

        The user may have requested help on a topic, return a dict of which
        topics to display. @chosen_topic has prescan_for_flag's return type

        :returns: dict

        """
        # topics maps each topic to whether it should be documented by
        # argparse on the command line
        if chosen_topic == "auth":
            chosen_topic = "certonly"
        if chosen_topic == "everything":
            chosen_topic = "run"
        if chosen_topic == "all":
            return dict([(t, True) for t in self.help_topics])
        elif not chosen_topic:
            return dict([(t, False) for t in self.help_topics])
        else:
            return dict([(t, t == chosen_topic) for t in self.help_topics])


def prepare_and_parse_args(plugins, args):
    """Returns parsed command line arguments.

    :param .PluginsRegistry plugins: available plugins
    :param list args: command line arguments with the program name removed

    :returns: parsed command line arguments
    :rtype: argparse.Namespace

    """
    helpful = HelpfulArgumentParser(args, plugins)

    # --help is automatically provided by argparse
    helpful.add(
        None, "-v", "--verbose", dest="verbose_count", action="count",
        default=flag_default("verbose_count"), help="This flag can be used "
        "multiple times to incrementally increase the verbosity of output, "
        "e.g. -vvv.")
    helpful.add(
        None, "-t", "--text", dest="text_mode", action="store_true",
        help="Use the text output instead of the curses UI.")
    helpful.add(
        None, "--register-unsafely-without-email", action="store_true",
        help="Specifying this flag enables registering an account with no "
             "email address. This is strongly discouraged, because in the "
             "event of key loss or account compromise you will irrevocably "
             "lose access to your account. You will also be unable to receive "
             "notice about impending expiration of revocation of your "
             "certificates. Updates to the Subscriber Agreement will still "
             "affect you, and will be effective 14 days after posting an "
             "update to the web site.")
    helpful.add(None, "-m", "--email", help=config_help("email"))
    # positional arg shadows --domains, instead of appending, and
    # --domains is useful, because it can be stored in config
    #for subparser in parser_run, parser_auth, parser_install:
    #    subparser.add_argument("domains", nargs="*", metavar="domain")
    helpful.add(None, "-d", "--domains", "--domain", dest="domains",
                metavar="DOMAIN", action=DomainFlagProcessor, default=[],
                help="Domain names to apply. For multiple domains you can use "
                "multiple -d flags or enter a comma separated list of domains "
                "as a parameter.")
    helpful.add(
        None, "--duplicate", dest="duplicate", action="store_true",
        help="Allow getting a certificate that duplicates an existing one")

    helpful.add_group(
        "automation",
        description="Arguments for automating execution & other tweaks")
    helpful.add(
        "automation", "--version", action="version",
        version="%(prog)s {0}".format(letsencrypt.__version__),
        help="show program's version number and exit")
    helpful.add(
        "automation", "--renew-by-default", action="store_true",
        help="Select renewal by default when domains are a superset of a "
             "previously attained cert")
    helpful.add(
        "automation", "--agree-tos", dest="tos", action="store_true",
        help="Agree to the Let's Encrypt Subscriber Agreement")
    helpful.add(
        "automation", "--account", metavar="ACCOUNT_ID",
        help="Account ID to use")

    helpful.add_group(
        "testing", description="The following flags are meant for "
        "testing purposes only! Do NOT change them, unless you "
        "really know what you're doing!")
    helpful.add(
        "testing", "--debug", action="store_true",
        help="Show tracebacks in case of errors, and allow letsencrypt-auto "
             "execution on experimental platforms")
    helpful.add(
        "testing", "--no-verify-ssl", action="store_true",
        help=config_help("no_verify_ssl"),
        default=flag_default("no_verify_ssl"))
    helpful.add(
        "testing", "--tls-sni-01-port", type=int,
        default=flag_default("tls_sni_01_port"),
        help=config_help("tls_sni_01_port"))
    helpful.add(
        "testing", "--http-01-port", type=int, dest="http01_port",
        default=flag_default("http01_port"), help=config_help("http01_port"))

    helpful.add_group(
        "security", description="Security parameters & server settings")
    helpful.add(
        "security", "--rsa-key-size", type=int, metavar="N",
        default=flag_default("rsa_key_size"), help=config_help("rsa_key_size"))
    helpful.add(
        "security", "--redirect", action="store_true",
        help="Automatically redirect all HTTP traffic to HTTPS for the newly "
             "authenticated vhost.", dest="redirect", default=None)
    helpful.add(
        "security", "--no-redirect", action="store_false",
        help="Do not automatically redirect all HTTP traffic to HTTPS for the newly "
             "authenticated vhost.", dest="redirect", default=None)
    helpful.add(
        "security", "--hsts", action="store_true",
        help="Add the Strict-Transport-Security header to every HTTP response."
             " Forcing browser to use always use SSL for the domain."
             " Defends against SSL Stripping.", dest="hsts", default=False)
    helpful.add(
        "security", "--no-hsts", action="store_false",
        help="Do not automatically add the Strict-Transport-Security header"
             " to every HTTP response.", dest="hsts", default=False)
    helpful.add(
        "security", "--uir", action="store_true",
        help="Add the \"Content-Security-Policy: upgrade-insecure-requests\""
             " header to every HTTP response. Forcing the browser to use"
             " https:// for every http:// resource.", dest="uir", default=None)
    helpful.add(
        "security", "--no-uir", action="store_false",
        help=" Do not automatically set the \"Content-Security-Policy:"
        " upgrade-insecure-requests\" header to every HTTP response.",
        dest="uir", default=None)
    helpful.add(
        "security", "--strict-permissions", action="store_true",
        help="Require that all configuration files are owned by the current "
             "user; only needed if your config is somewhere unsafe like /tmp/")

    helpful.add_deprecated_argument("--agree-dev-preview", 0)

    _create_subparsers(helpful)
    _paths_parser(helpful)
    # _plugins_parsing should be the last thing to act upon the main
    # parser (--help should display plugin-specific options last)
    _plugins_parsing(helpful, plugins)

    return helpful.parse_args()


def _create_subparsers(helpful):
    helpful.add_group("certonly", description="Options for modifying how a cert is obtained")
    helpful.add_group("install", description="Options for modifying how a cert is deployed")
    helpful.add_group("revoke", description="Options for revocation of certs")
    helpful.add_group("rollback", description="Options for reverting config changes")
    helpful.add_group("plugins", description="Plugin options")
    helpful.add(
        None, "--user-agent", default=None,
        help="Set a custom user agent string for the client. User agent strings allow "
             "the CA to collect high level statistics about success rates by OS and "
             "plugin. If you wish to hide your server OS version from the Let's "
             'Encrypt server, set this to "".')
    helpful.add("certonly",
                "--csr", type=read_file,
                help="Path to a Certificate Signing Request (CSR) in DER"
                " format; note that the .csr file *must* contain a Subject"
                " Alternative Name field for each domain you want certified.")
    helpful.add("rollback",
                "--checkpoints", type=int, metavar="N",
                default=flag_default("rollback_checkpoints"),
                help="Revert configuration N number of checkpoints.")
    helpful.add("plugins",
                "--init", action="store_true", help="Initialize plugins.")
    helpful.add("plugins",
                "--prepare", action="store_true", help="Initialize and prepare plugins.")
    helpful.add("plugins",
                "--authenticators", action="append_const", dest="ifaces",
                const=interfaces.IAuthenticator, help="Limit to authenticator plugins only.")
    helpful.add("plugins",
                "--installers", action="append_const", dest="ifaces",
                const=interfaces.IInstaller, help="Limit to installer plugins only.")


def _paths_parser(helpful):
    add = helpful.add
    verb = helpful.verb
    if verb == "help":
        verb = helpful.help_arg
    helpful.add_group(
        "paths", description="Arguments changing execution paths & servers")

    cph = "Path to where cert is saved (with auth --csr), installed from or revoked."
    section = "paths"
    if verb in ("install", "revoke", "certonly"):
        section = verb
    if verb == "certonly":
        add(section, "--cert-path", type=os.path.abspath,
            default=flag_default("auth_cert_path"), help=cph)
    elif verb == "revoke":
        add(section, "--cert-path", type=read_file, required=True, help=cph)
    else:
        add(section, "--cert-path", type=os.path.abspath,
            help=cph, required=(verb == "install"))

    section = "paths"
    if verb in ("install", "revoke"):
        section = verb
    # revoke --key-path reads a file, install --key-path takes a string
    add(section, "--key-path", required=(verb == "install"),
        type=((verb == "revoke" and read_file) or os.path.abspath),
        help="Path to private key for cert installation "
             "or revocation (if account key is missing)")

    default_cp = None
    if verb == "certonly":
        default_cp = flag_default("auth_chain_path")
    add("paths", "--fullchain-path", default=default_cp, type=os.path.abspath,
        help="Accompanying path to a full certificate chain (cert plus chain).")
    add("paths", "--chain-path", default=default_cp, type=os.path.abspath,
        help="Accompanying path to a certificate chain.")
    add("paths", "--config-dir", default=flag_default("config_dir"),
        help=config_help("config_dir"))
    add("paths", "--work-dir", default=flag_default("work_dir"),
        help=config_help("work_dir"))
    add("paths", "--logs-dir", default=flag_default("logs_dir"),
        help="Logs directory.")
    add("paths", "--server", default=flag_default("server"),
        help=config_help("server"))


def _plugins_parsing(helpful, plugins):
    helpful.add_group(
        "plugins", description="Let's Encrypt client supports an "
        "extensible plugins architecture. See '%(prog)s plugins' for a "
        "list of all installed plugins and their names. You can force "
        "a particular plugin by setting options provided below. Further "
        "down this help message you will find plugin-specific options "
        "(prefixed by --{plugin_name}).")
    helpful.add(
        "plugins", "-a", "--authenticator", help="Authenticator plugin name.")
    helpful.add(
        "plugins", "-i", "--installer", help="Installer plugin name (also used to find domains).")
    helpful.add(
        "plugins", "--configurator", help="Name of the plugin that is "
        "both an authenticator and an installer. Should not be used "
        "together with --authenticator or --installer.")
    helpful.add("plugins", "--apache", action="store_true",
                help="Obtain and install certs using Apache")
    helpful.add("plugins", "--nginx", action="store_true",
                help="Obtain and install certs using Nginx")
    helpful.add("plugins", "--standalone", action="store_true",
                help='Obtain certs using a "standalone" webserver.')
    helpful.add("plugins", "--manual", action="store_true",
                help='Provide laborious manual instructions for obtaining a cert')
    helpful.add("plugins", "--webroot", action="store_true",
                help='Obtain certs by placing files in a webroot directory.')

    # things should not be reorder past/pre this comment:
    # plugins_group should be displayed in --help before plugin
    # specific groups (so that plugins_group.description makes sense)

    helpful.add_plugin_args(plugins)

    # These would normally be a flag within the webroot plugin, but because
    # they are parsed in conjunction with --domains, they live here for
    # legibiility. helpful.add_plugin_ags must be called first to add the
    # "webroot" topic
    helpful.add("webroot", "-w", "--webroot-path", action=WebrootPathProcessor,
                help="public_html / webroot path. This can be specified multiple times to "
                     "handle different domains; each domain will have the webroot path that"
                     " preceded it.  For instance: `-w /var/www/example -d example.com -d "
                     "www.example.com -w /var/www/thing -d thing.net -d m.thing.net`")
    parse_dict = lambda s: dict(json.loads(s))
    # --webroot-map still has some awkward properties, so it is undocumented
    helpful.add("webroot", "--webroot-map", default={}, type=parse_dict,
                help=argparse.SUPPRESS)


class WebrootPathProcessor(argparse.Action): # pylint: disable=missing-docstring
    def __init__(self, *args, **kwargs):
        self.domain_before_webroot = False
        argparse.Action.__init__(self, *args, **kwargs)

    def __call__(self, parser, config, webroot, option_string=None):
        """
        Keep a record of --webroot-path / -w flags during processing, so that
        we know which apply to which -d flags
        """
        if config.webroot_path is None:      # first -w flag encountered
            config.webroot_path = []
            # if any --domain flags preceded the first --webroot-path flag,
            # apply that webroot path to those; subsequent entries in
            # config.webroot_map are filled in by cli.DomainFlagProcessor
            if config.domains:
                self.domain_before_webroot = True
                for d in config.domains:
                    config.webroot_map.setdefault(d, webroot)
        elif self.domain_before_webroot:
            # FIXME if you set domains in a config file, you should get a different error
            # here, pointing you to --webroot-map
            raise errors.Error("If you specify multiple webroot paths, one of "
                               "them must precede all domain flags")
        config.webroot_path.append(webroot)


class DomainFlagProcessor(argparse.Action): # pylint: disable=missing-docstring
    def __call__(self, parser, config, domain_arg, option_string=None):
        """
        Process a new -d flag, helping the webroot plugin construct a map of
        {domain : webrootpath} if -w / --webroot-path is in use
        """
        for domain in (d.strip() for d in domain_arg.split(",")):
            if domain not in config.domains:
                config.domains.append(domain)
                # Each domain has a webroot_path of the most recent -w flag
                if config.webroot_path:
                    config.webroot_map[domain] = config.webroot_path[-1]


def setup_log_file_handler(args, logfile, fmt):
    """Setup file debug logging."""
    log_file_path = os.path.join(args.logs_dir, logfile)
    handler = logging.handlers.RotatingFileHandler(
        log_file_path, maxBytes=2 ** 20, backupCount=10)
    # rotate on each invocation, rollover only possible when maxBytes
    # is nonzero and backupCount is nonzero, so we set maxBytes as big
    # as possible not to overrun in single CLI invocation (1MB).
    handler.doRollover()  # TODO: creates empty letsencrypt.log.1 file
    handler.setLevel(logging.DEBUG)
    handler_formatter = logging.Formatter(fmt=fmt)
    handler_formatter.converter = time.gmtime  # don't use localtime
    handler.setFormatter(handler_formatter)
    return handler, log_file_path


def _cli_log_handler(args, level, fmt):
    if args.text_mode:
        handler = colored_logging.StreamHandler()
        handler.setFormatter(logging.Formatter(fmt))
    else:
        handler = log.DialogHandler()
        # dialog box is small, display as less as possible
        handler.setFormatter(logging.Formatter("%(message)s"))
    handler.setLevel(level)
    return handler


def setup_logging(args, cli_handler_factory, logfile):
    """Setup logging."""
    fmt = "%(asctime)s:%(levelname)s:%(name)s:%(message)s"
    level = -args.verbose_count * 10
    file_handler, log_file_path = setup_log_file_handler(
        args, logfile=logfile, fmt=fmt)
    cli_handler = cli_handler_factory(args, level, fmt)

    # TODO: use fileConfig?

    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)  # send all records to handlers
    root_logger.addHandler(cli_handler)
    root_logger.addHandler(file_handler)

    logger.debug("Root logging level set at %d", level)
    logger.info("Saving debug log to %s", log_file_path)


def _handle_exception(exc_type, exc_value, trace, args):
    """Logs exceptions and reports them to the user.

    Args is used to determine how to display exceptions to the user. In
    general, if args.debug is True, then the full exception and traceback is
    shown to the user, otherwise it is suppressed. If args itself is None,
    then the traceback and exception is attempted to be written to a logfile.
    If this is successful, the traceback is suppressed, otherwise it is shown
    to the user. sys.exit is always called with a nonzero status.

    """
    logger.debug(
        "Exiting abnormally:%s%s",
        os.linesep,
        "".join(traceback.format_exception(exc_type, exc_value, trace)))

    if issubclass(exc_type, Exception) and (args is None or not args.debug):
        if args is None:
            logfile = "letsencrypt.log"
            try:
                with open(logfile, "w") as logfd:
                    traceback.print_exception(
                        exc_type, exc_value, trace, file=logfd)
            except:  # pylint: disable=bare-except
                sys.exit("".join(
                    traceback.format_exception(exc_type, exc_value, trace)))

        if issubclass(exc_type, errors.Error):
            sys.exit(exc_value)
        else:
            # Here we're passing a client or ACME error out to the client at the shell
            # Tell the user a bit about what happened, without overwhelming
            # them with a full traceback
            err = traceback.format_exception_only(exc_type, exc_value)[0]
            # Typical error from the ACME module:
            # acme.messages.Error: urn:acme:error:malformed :: The request message was
            # malformed :: Error creating new registration :: Validation of contact
            # mailto:none@longrandomstring.biz failed: Server failure at resolver
            if ("urn:acme" in err and ":: " in err
                and args.verbose_count <= flag_default("verbose_count")):
                # prune ACME error code, we have a human description
                _code, _sep, err = err.partition(":: ")
            msg = "An unexpected error occurred:\n" + err + "Please see the "
            if args is None:
                msg += "logfile '{0}' for more details.".format(logfile)
            else:
                msg += "logfiles in {0} for more details.".format(args.logs_dir)
            sys.exit(msg)
    else:
        sys.exit("".join(
            traceback.format_exception(exc_type, exc_value, trace)))


def main(cli_args=sys.argv[1:]):
    """Command line argument parsing and main script execution."""
    sys.excepthook = functools.partial(_handle_exception, args=None)

    # note: arg parser internally handles --help (and exits afterwards)
    plugins = plugins_disco.PluginsRegistry.find_all()
    args = prepare_and_parse_args(plugins, cli_args)
    config = configuration.NamespaceConfig(args)
    zope.component.provideUtility(config)

    # Setup logging ASAP, otherwise "No handlers could be found for
    # logger ..." TODO: this should be done before plugins discovery
    for directory in config.config_dir, config.work_dir:
        le_util.make_or_verify_dir(
            directory, constants.CONFIG_DIRS_MODE, os.geteuid(),
            "--strict-permissions" in cli_args)
    # TODO: logs might contain sensitive data such as contents of the
    # private key! #525
    le_util.make_or_verify_dir(
        args.logs_dir, 0o700, os.geteuid(), "--strict-permissions" in cli_args)
    setup_logging(args, _cli_log_handler, logfile='letsencrypt.log')

    logger.debug("letsencrypt version: %s", letsencrypt.__version__)
    # do not log `args`, as it contains sensitive data (e.g. revoke --key)!
    logger.debug("Arguments: %r", cli_args)
    logger.debug("Discovered plugins: %r", plugins)

    sys.excepthook = functools.partial(_handle_exception, args=args)

    # Displayer
    if args.text_mode:
        displayer = display_util.FileDisplay(sys.stdout)
    else:
        displayer = display_util.NcursesDisplay()
    zope.component.provideUtility(displayer)

    # Reporter
    report = reporter.Reporter()
    zope.component.provideUtility(report)
    atexit.register(report.atexit_print_messages)

    if not os.geteuid() == 0:
        logger.warning(
            "Root (sudo) is required to run most of letsencrypt functionality.")
        # check must be done after arg parsing as --help should work
        # w/o root; on the other hand, e.g. "letsencrypt run
        # --authenticator dns" or "letsencrypt plugins" does not
        # require root as well
        #return (
        #    "{0}Root is required to run letsencrypt.  Please use sudo.{0}"
        #    .format(os.linesep))

    return args.func(args, config, plugins)

if __name__ == "__main__":
    err_string = main()
    if err_string:
        logger.warn("Exiting with message %s", err_string)
    sys.exit(err_string)  # pragma: no cover
