<commit_before># Copyright Hybrid Logic Ltd.  See LICENSE file for details.

"""
The command-line certificate authority tool.
"""

import os
import sys

from twisted.internet.defer import maybeDeferred, Deferred
from twisted.python.filepath import FilePath
from twisted.python.usage import Options, UsageError

from zope.interface import implementer

from ..common.script import (flocker_standard_options, ICommandLineScript,
                             FlockerScriptRunner)

from ._ca import (CertificateAuthority, CertificateAlreadyExistsError,
                  KeyAlreadyExistsError)


class InitializeOptions(Options):
    """
    Command line for ``flocker-ca initialize``.
    """

    longdesc = """Create a new certificate authority.

    Creates a private/public key pair and self-signs the public key to
    produce a new certificate authority root certificate. These are stored
    in the current working directory. Once this has been done other
    ``flocker-ca`` commands can be run in this directory to create
    certificates singed by this particular certificate authority.

    Parameters:

    * name: Will be used as the name of the certificate authority,
      e.g. "mycluster".
    """

    synoposis = "<name>"

    def parseArgs(self, name):
        self["name"] = name
        self["path"] = FilePath(os.getcwd())

    def run(self):
        # Check if files already exist in current directory. If they do
        # error out. Otherwise calling APIs on CertificateAuthority,
        # create new private/public key pair, self-sign, write out to
        # files locally.
        d = Deferred()

        def generateCert(_):
            try:
                CertificateAuthority.initialize(self["path"], self["name"])
                print (
                    b"Created cluster.key and cluster.crt. "
                    "Please keep cluster.key secret, as anyone who can access "
                    "will be able to control your cluster."
                )
            except CertificateAlreadyExistsError as e:
                raise UsageError(str(e))
            except KeyAlreadyExistsError as e:
                raise UsageError(str(e))

        def generateError(failure):
            print b"Error: {error}".format(error=str(failure.value))
            sys.exit(1)

        d.addCallback(generateCert)
        d.addErrback(generateError)
        d.callback(None)
        return d


@flocker_standard_options
class CAOptions(Options):
    """
    Command line options for ``flocker-ca``.
    """
    longdesc = """flocker-ca is used to create TLS certificates.

    The certificates are used to identify the control service, nodes and
    API clients within a Flocker cluster.
    """

    synoposis = "Usage: flocker-ca <command> [OPTIONS]"

    subCommands = [
        ["initialize", None, InitializeOptions,
         ("Initialize a certificate authority in the "
          "current working directory.")]<commit_msg>fix typo<commit_after># Copyright Hybrid Logic Ltd.  See LICENSE file for details.

"""
The command-line certificate authority tool.
"""

import os
import sys

from twisted.internet.defer import maybeDeferred, Deferred
from twisted.python.filepath import FilePath
from twisted.python.usage import Options, UsageError

from zope.interface import implementer

from ..common.script import (flocker_standard_options, ICommandLineScript,
                             FlockerScriptRunner)

from ._ca import (CertificateAuthority, CertificateAlreadyExistsError,
                  KeyAlreadyExistsError)


class InitializeOptions(Options):
    """
    Command line for ``flocker-ca initialize``.
    """

    longdesc = """Create a new certificate authority.

    Creates a private/public key pair and self-signs the public key to
    produce a new certificate authority root certificate. These are stored
    in the current working directory. Once this has been done other
    ``flocker-ca`` commands can be run in this directory to create
    certificates singed by this particular certificate authority.

    Parameters:

    * name: Will be used as the name of the certificate authority,
      e.g. "mycluster".
    """

    synoposis = "<name>"

    def parseArgs(self, name):
        self["name"] = name
        self["path"] = FilePath(os.getcwd())

    def run(self):
        # Check if files already exist in current directory. If they do
        # error out. Otherwise calling APIs on CertificateAuthority,
        # create new private/public key pair, self-sign, write out to
        # files locally.
        d = Deferred()

        def generateCert(_):
            try:
                CertificateAuthority.initialize(self["path"], self["name"])
                print (
                    b"Created cluster.key and cluster.crt. "
                    "Please keep cluster.key secret, as anyone who can access "
                    "will be able to control your cluster."
                )
            except CertificateAlreadyExistsError as e:
                raise UsageError(str(e))
            except KeyAlreadyExistsError as e:
                raise UsageError(str(e))

        def generateError(failure):
            print b"Error: {error}".format(error=str(failure.value))
            sys.exit(1)

        d.addCallback(generateCert)
        d.addErrback(generateError)
        d.callback(None)
        return d


@flocker_standard_options
class CAOptions(Options):
    """
    Command line options for ``flocker-ca``.
    """
    longdesc = """flocker-ca is used to create TLS certificates.

    The certificates are used to identify the control service, nodes and
    API clients within a Flocker cluster.
    """

    synopsis = "Usage: flocker-ca <command> [OPTIONS]"

    subCommands = [
        ["initialize", None, InitializeOptions,
         ("Initialize a certificate authority in the "
          "current working directory.")]
{'fraction_non_alphanumeric': 0.0807327001356852, 'fraction_numerical': 0.00033921302578018993, 'mean_word_length': 2.4688235294117646, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '196535', 'n_tokens_mistral': 1528, 'n_tokens_neox': 1449, 'n_words': 534}